Is there a way to set the checkbox value (False/True) by code? I have a checkbox that doesn’t retain its value when I switch between pages of page=st.sidebar.selectbox. For example, I click the checkbox, then switch the page, and when I get back to original page where the checkbox is, it is unchecked. This should be simple but couldn’t seem to get it working; see below. Appreciate any comments.
if 'BoundingStiffnessFlag' not in st.session_state:
st.session_state.BoundingStiffnessFlag = st.checkbox('Enable Bounding Stiffness Analysis',value=False, on_change=BoundingStiffnessFlag_callback_fcn, key='BoundingStiffnessFlag_Key')
#
st.session_state.BoundingStiffnessFlag_Key = st.session_state.BoundingStiffnessFlag
def Page_on_change_callback_fcn():
if 'BoundingStiffnessFlag' in st.session_state:
st.session_state.BoundingStiffnessFlag= st.session_state.BoundingStiffnessFlag_Key
For multi-pages app we need to create a session variable and assign it to the value so that it will be seen by other pages too. Session variables are visible to other pages.
This is our main page. Please pay attention to the comments.
streamlit_app.py
import streamlit as st
from streamlit import session_state as ss
# Define a session variable to store the state of the checkbox
# and assign it to the value parameter of the said checkbox.
if 'absent' not in ss:
ss.absent = False
def update():
"""A function to be called once there is a change in the checkbox.
This is an oppurtunity for us to assign the checkbox
value to our session variable.
"""
ss.absent = ss.cb
# This checkbox is a bit busy, we use the value, key and on_change parameters.
st.checkbox(label='Absent', value=ss.absent, key='cb', on_change=update)
st.write(f'Absent: {ss.absent}')
selected = st.selectbox('Select Page', options=[None, 'page1', 'page2'])
if selected:
st.switch_page(f'pages/{selected}.py')
In other pages.
pages/page1.py and pages/page2.py
import streamlit as st
from streamlit import session_state as ss
# Define it here too, in case of page refresh, we will not get an error.
if 'absent' not in ss:
ss.absent = False
st.write(f'Absent: {ss.absent}')
We use two pages to test if the value of our session variable will persist if the users navigate from page1 to page2 and vice versa.