Use button to clear multiselect using session_state

Hi @Marisa_Smith , can you show us how to apply st.sessions_state on the mulit-selectbox? Cause I am facing an issue of unchecking all the values on the multi-selectbox? Would be appreciate if you can help to resolve such issue! Thanks

hi @jiffred_teh!

Sorry for my delay in getting this example to you. Here is an example code that does exactly what your looking for:

import streamlit as st

# create a function that sets the value in state back to an empty list
def clear_multi():
    st.session_state.multiselect = []
    return

st.title("Clear multiselect with stateful button")

# create multiselect and automatically put it in state with its key parameter
multi = st.multiselect("Pick an option", ["a","b","c","d"], key="multiselect")

# check state
st.session_state

#create your button to clear the state of the multiselect
st.button("Clear multiselect", on_click=clear_multi)

Happy Streamlit-ing!
Marisa

P.S. I moved your question to its own topic to make it easier for others to find

2 Likes

Hi Marisa,
I have a follow-up question and hope you could help me out: In my current project I am doing the same thing as asked in this thread, i.e. clearing a multiselect widget ms upon another selectbox widget sb changes its value. So I am using the callback function of sb to achieve this.
I am able to clear ms if I assign an empty list to the key ms within the session_state, like you did:

def callback():
    st.session_state['ms']=[]
    return

However, it doesn’t seem to work if I instead invoke .clear() in the list object within session_state itself or try to clear the list using del (as suggested in the python docs):

def callback():
    st.session_state['ms'].clear()   # not working
    del st.session_state['ms'][:]  # not working either

    return

Why are the later solutions not working when applied to a list within session_state?

This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.