Search code examples
pythonstreamlit

How to programatically check/uncheck all checkboxes?


I have created a list of checkboxes in the loop (for every row in the dataframe):

options = []
for idx, row in df.iterrows():
    option = st.sidebar.checkbox(label=f"{row['title']} ({row['option']})", key=idx)
    options.append([row['title'], option])

By default, all the checkboxes are unchecked which is as desired.

Upon checking/unchecking any checkbox, the interface is updated, which is also ok. In order not to check/uncheck every checkbox in case the user wants so select/deselect all, I have created buttons and assigned the function calls:

def select_all_fields():
    options = []
    for idx, row in gdf_paper_dry_run.iterrows():
        option = st.sidebar.checkbox(label=f"{row['label']} ({row['option']})", key=idx, value=True)
        options.append([row['label'], option])
        
def clear_all_fields(options_list):
    options = []
    for idx, row in gdf_paper_dry_run.iterrows():
        option = st.sidebar.checkbox(label=f"{row['label']} ({row['option']})", key=idx, value=False)
        options.append([row['label'], option])

This, however, doesn't work. Does anyone know how to select/deselect all the checkboxes from the list programmatically?


Solution

  • Use a combination of callback and session_states.

    import streamlit as st
    
    
    def sel_callback():
        st.session_state.a = st.session_state.sel
        st.session_state.b = st.session_state.sel
    
    st.write('### Control')
    st.checkbox('select all', key='sel', on_change=sel_callback)
    
    st.write('### main')
    st.checkbox('a', key='a')
    st.checkbox('b', key='b')
    

    Output

    enter image description here