Turn off toggle after file upload

uploaded_file = st.file_uploader("Choose a file", type=['csv', 'xlsx', 'xls', 'xlsm', 'xlsb'])
sample_file = st.toggle("Toggle to use a sample file")

If a user initially switches on the toggle to use a sample file, how do I turn off the toggle once a file is uploaded?

Hey @OOlajide, welcome back to our forum! Itโ€™s been a while :balloon:

Whenever you want to persist data across sessions, you generally want to use st.session_state. Hereโ€™s an example:


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

uploaded_file = st.file_uploader("Choose a file", type=['csv', 'xlsx', 'xls', 'xlsm', 'xlsb'])

if uploaded_file is not None:
    st.session_state["toggle_sample_file_value"] = False

sample_file = st.toggle("Toggle to use a sample file", value=st.session_state["toggle_sample_file_value"])
2 Likes

Thanks Arnaud, but Iโ€™d like the toggle to be off by default. So if I toggle on to use a sample file first, then decide to upload a file after, the toggle should switch off after the file upload. I tried the code below but no luck so farโ€ฆ

if "toggle_sample_file_value" not in st.session_state:
    st.session_state["toggle_sample_file_value"] = False

uploaded_file = st.file_uploader("Choose a file", type=['csv', 'xlsx', 'xls', 'xlsm', 'xlsb'])

if uploaded_file is not None:
    st.session_state["toggle_sample_file_value"] = False

sample_file = st.toggle("Toggle to use a sample file", value=st.session_state["toggle_sample_file_value"])