Session state issue with st.checkbox

Hi @tarmojuristo, welcome to the community!! :partying_face: :wave:

Here’s a solution that uses callbacks to avoid the issue of having to interact with the widget twice:

Code

import streamlit as st

# callback to update 'test' based on 'check'
def flip():
    if st.session_state["check"]:
        st.session_state["test"] = True
    else:
        st.session_state["test"] = False

if "test" not in st.session_state:
    st.session_state["test"] = True

st.checkbox(
    "Flip the switch", value=st.session_state["test"], key="check", on_change=flip
)

st.write(st.session_state["test"])

Output

checkbox-state

Happy Streamlit-ing! :balloon:
Snehan

2 Likes