Streamlit Checkbox

Hi Everyone,

I am new to streamlit and i am creating a webpage and in that I have a question and want to have four checkboxes for it, if first 2 are checked than next two should be disabled, when third is checked then 1,2 and 4 should be disabled, when 4 is selected then all of the above should be disabled, how can this be possible.

Hi @Manish3

You seem to have missed some conditions in your description:

  1. What if either 1st one or the 2nd one is individually selected? What needs to be done then?
  2. If the 3rd one is selected, checkbox #4 will be disabled. So the 4th checkbox will never be able to be selected after selecting the 3rd checkbox.

You will be able to implement the above for 1 single run, not for multiple iterations. You need to think about all relevant conditions / combinations of selecting and disabling the checkboxes before proceeding ahead.

Cheers

The logic to disable the checkboxes could be implemented as a callback function that relies on the st.session_state:

multiple checkboxes

Code:
import streamlit as st

def disable_checkboxes():
    ## Dict with the disable conditions
    disable = st.session_state.disable

    ## Current checkboxes' values
    chk1, chk2, chk3, chk4 = (
        st.session_state.chk1,
        st.session_state.chk2,
        st.session_state.chk3,
        st.session_state.chk4,
    )

    ## Logic to disable checkboxes
    disable[1] = chk3 or chk4
    disable[2] = chk3 or chk4
    disable[3] = (chk1 and chk2) or chk4
    disable[4] = (chk1 and chk2) or chk3


def main():
    if "disable" not in st.session_state:
        st.session_state.disable = {1: False, 2: False, 3: False, 4: False}

    "**✔️ Disabling Checkboxes and Session State**"

    disable = st.session_state.disable

    st.checkbox("First", disabled=disable[1], on_change=disable_checkboxes, key="chk1")
    st.checkbox("Second", disabled=disable[2], on_change=disable_checkboxes, key="chk2")
    st.checkbox("Third", disabled=disable[3], on_change=disable_checkboxes, key="chk3")
    st.checkbox("Fourth", disabled=disable[4], on_change=disable_checkboxes, key="chk4")


if __name__ == "__main__":
    main()
3 Likes

Hi Edsaac,

Thank you very much for your help here, i was struggling since last few days and it worked perfectly for me.

your code is just awesome!!

Thanks again,
Manish

Hi Shawn,

Finally!! thanks for asking this, I have added a another condition in the edsaac’s code, if 1 or 2 is selected then also 3 and 4 should be disabled.

Thanks,
Manish

1 Like

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.