Skip to content
Advertisement

Removing the selected items from streamlet’s multiselect

I am trying to delete objects from a list by choosing them via streamlits multiselect widget, having the list entries as entries of the widget. Thus, the list also decides what options are in the multiselect box. However, after the app reruns—once I deleted some options—I get the error: streamlit.errors.StreamlitAPIException: Every Multiselect default value must exist in options

Here is some minimal code example.

import streamline as st

if st.button("Refill") or "options" not in st.session_state:
    st.session_state.options=["a","b","c"]

def submit():
    for item in st.session_state.selected:
        st.session_state.options.remove(item)

form=st.form("My form")
form.multiselect("Select", st.session_state.options, key="selected")
form.form_submit_button("Submit", on_click=submit)

I tried to add the line st.session_state.selected=[] to the submit function so that the multiselect-box is cleared and does not reference deleted items, but it did not solve the issue.

Thanks for any help in advance! :)

Advertisement

Answer

Add the following to the top of your code:

if "selected" in st.session_state:
    del st.session_state.selected

Explanation: The streamlit multi-select widget maintains the last selection in its internal state (st.session_state.selected in your case), so if you delete an item from your st.session_state.options list, it will error out, as it can’t find the current selection in the list you passed to it.

To fix this, simply delete the session_state.selected prior to running the rest of the code; this is done with the suggested if-Statement.

You might also want to add the kwarg clear_on_submit=True on your st.form definition, as that clears the input of the form as well.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement