Thanks @Shawn_Pereira . For me, the code is susceptible the issue I mentioned: it won’t mix and match well if a user manually expands/collapses things in addition to using the next buttons.
Suppose session state thinks an expander is closed, but a user clicks on it to expand it. This is done in browser and does not report back to session state. If you attempt to close it with session state, nothing will happen since you won’t actually be changing the parameters of the element.
With your code:
I see three ways around this:
- with javascript
- with manual destruction and recreation of the expander elements so they start as if new with each forced state
- using experimental rerun to “cycle” the expander through first the opposite of what you want, then what you want so it registers a definite “change of state”
If you just want to ensure you are opening the next one, you can add that cycling behavior (note this will not force the state of all the expanders if the user has pulled them out of sync with what session state thinks, though it’d be an easy addition if you really did want to force the state of all of them).
import streamlit as st
if 'cycle' not in st.session_state:
st.session_state.cycle = -1
if "etgl" not in st.session_state:
st.session_state.etgl = [True, False, False]
with st.expander('Expander1', st.session_state.etgl[0]):
st.write("In expander 1")
if st.button("Next", key="b1"):
st.session_state.etgl = [False, False, False]
st.session_state.cycle = 1
st.experimental_rerun()
with st.expander('Expander2', st.session_state.etgl[1]):
st.write("In expander 2")
if st.button("Next", key="b2"):
st.session_state.etgl = [False, False, False]
st.session_state.cycle = 2
st.experimental_rerun()
with st.expander('Expander3', st.session_state.etgl[2]):
st.write("In expander 3")
if st.button("Next", key="b3"):
st.session_state.etgl = [False, False, False]
st.session_state.cycle = 0
st.experimental_rerun()
if st.session_state.cycle >= 0:
st.session_state.etgl[st.session_state.cycle] = True
st.session_state.cycle = -1
st.experimental_rerun()