Auto-collapse an expander in a form

Hi @dataprofessor

Thanks! I have a related but different problem now, where a button only closes the expander the first time. But if one manually opens the expander, the button no longer works:

import streamlit as st

st.write("The button can only close the expander the first time! And not after the expander is manually opened.")

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

def toggle_closed():
    # <potentially do other actions>
    st.session_state["expander_state"] = False

st.button("do stuff then close expander",on_click=toggle_closed)

with st.expander("test expander",expanded = st.session_state["expander_state"]):
    st.write("expander is open")

It seems to me that buttons can only toggle expanders if the expanded keyword in the expander definition changes.

The challenge is that one can’t ensure that the expander is only opened by a button that toggles the expander definition (indeed, the intuitive thing for people is to open the expander directly instead of via some other toggling button, which is also a clunky UX experience).

Thanks!

EDIT: mathcatsand helped me with this here: https://discuss.streamlit.io/t/control-state-of-st-expander/35816/7. The key was to force a re-definition and rerun, and to put in a time delay to ensure the front-end and back-end sync up.