How to disable one checkbox, when another checkbox or checkboxes are checked in streamlit?

I am designing a Streamlit app that has four checkboxes and allows to select three different functions.
I would like to impose a condition on these checkboxes that if the checkbox(s) for Function 1 to Function 3 are checked (multiple or single), then the checkbox for ‘All’ should be disabled. Currently, if the ‘All’ checkbox is checked, all other checkboxes will be checked as well, this is as required for the app. I understand there is a ‘disabled’ parameter associated with the checkbox widget. But I do not know how to implement this feature to achieve my goal. Any form of help would be appreciated.

I am using Python 3.10.4, Streamlit 1.11.1, Virtualenv, PyCharm Community Edition 2022.1.4, Windows 11, Firefox 103.0.1 (64-bit).

The code is shown here:

import streamlit as st


# Function 1
def func1():
    st.write("Function 1 executed.")


# Function 2
def func2():
    st.write("Function 2 executed.")


# Function 3
def func3():
    st.write("Function 3 executed.")


# function to run chosen function(s)
def execute():
    if cb2: func1()
    if cb3: func2()
    if cb4: func3()


# sidebar configurations
cb1 = st.sidebar.checkbox('All', key='a')
cb2 = st.sidebar.checkbox('Function 1', key='b', value=cb1)
cb3 = st.sidebar.checkbox('Function 2', key='c', value=cb1)
cb4 = st.sidebar.checkbox('Function 3', key='d', value=cb1)
run_btn = st.sidebar.button('Run', on_click=execute, key='e')

The creation of the checkboxes could be controlled with an if-else statement following the “All” checkbox, something like this:

import streamlit as st

def func1(): st.write("Function 1 executed.")
def func2(): st.write("Function 2 executed.")
def func3(): st.write("Function 3 executed.")

# function to run chosen function(s)
def execute():
    if cb1: func1()
    if cb2: func2()
    if cb3: func3()

# checkbox shenanigans 
cbAll = st.sidebar.checkbox("Select All")

if cbAll:
    cb1 = st.sidebar.checkbox("Func 1",value=cbAll,disabled=True,key=1)
    cb2 = st.sidebar.checkbox("Func 2",value=cbAll,disabled=True,key=2)
    cb3 = st.sidebar.checkbox("Func 3",value=cbAll,disabled=True,key=3)
else:
    cb1 = st.sidebar.checkbox("Func 1",key=4)
    cb2 = st.sidebar.checkbox("Func 2",key=5)
    cb3 = st.sidebar.checkbox("Func 3",key=6)

run_btn = st.sidebar.button('Run', on_click=execute, key='e')

checkboxes

For many functions/checkboxes, I’d rather use multiselect:
https://discuss.streamlit.io/t/select-all-on-a-streamlit-multiselect/9799/2

2 Likes