Search code examples
pythonstreamlit

How to check if a sidebar checkbox is clicked in streamlit app


I wrote the code as follows to create checkboxes for streamlit app in a for loop. How can I develop the code to check weather a box is clicked or not? I did it in the following way but it doesn't work in this way.


#I created data frame called df in another function.

names = ["df1","df2"]

def create_checkboxes (names :List[str], df):
  checkboxes = {}
  for name in names:
     checkboxes[name] = st.sidebar.checkbox(name, key=name, value=True)


  dfs = []
  for key, value in checkboxes.items():
      checkboxes[key] == "df1"
      dfs.append(df_list[0])
      checkboxes[key] == "df2"
      dfs.append(df_list[1])

   if len(dfs) > 1:
      df = pd.concat(dfs)

return df, checkboxes

Solution

  • You can try this approach, using an if condition.
    First set the checkboxex value to False, but you can still keep it as True if you want:

    checkboxes[name] = st.sidebar.checkbox(name, key=name, value=False)
    

    Refactor the loop to:

    ...
    dfs = []
    for key, value in checkboxes.items():
        if value:
            dfs.append(df[key])
    
    if len(dfs) > 1:
        df = pd.concat(dfs)
    ...