Skip to content

Instantly share code, notes, and snippets.

@skannan-maf
Last active June 10, 2024 07:51
Show Gist options
  • Save skannan-maf/9155164b017df8e0bbadc9751b6be788 to your computer and use it in GitHub Desktop.
Save skannan-maf/9155164b017df8e0bbadc9751b6be788 to your computer and use it in GitHub Desktop.
'''
Getting selectbox working in streamlit can be tricky.
1)
Sometimes, when we select an option, streamlit suddenly changes (in a quick flash) to the old option.
This can be unnerving at times.
This is because when streamlit re-renders your script after the option selection, the "widget key" in session state
is already populated with the value of new option.
So you need to pass that option's index while creating the selectbox.
2)
In a multi-page streamlit app, streamlit forgets the selected option when the user navigates away from a page
This gist has a fix for it
'''
def YourOption_select():
OptionDefaultIndex = 0
if 'YourOptionSelectButton_State' in st.session_state:
#
# YourOptionSelectButton_State : This is the widget key
#
# When user selects an option, the "widget key" in st.session_state is already populated with the option
# So we just find the option index and pass it while rendering the selectBox
#
try:
OptionDefaultIndex = GetYourOptions().index(st.session_state['YourOptionSelectButton_State'])
except:
OptionDefaultIndex = 0
#
# And delete the state of the widget key. Earlier, it used to work without this.
# However, I encountered an issue where this function was not returning the correct value although
# the user selection is reflected in the UI.
# Debugging that issue, I found that deleting the widget key and redrawing the widget fresh everytime helps
# Most likely, this is serving as a workaround for a streamlit bug
#
del st.session_state['YourOptionSelectButton_State']
elif 'YourOptionSelectButton_State_Backup' in st.session_state:
#
# Sometimes, when we stray out of a page to another page that does not have this widget,
# then streamlit erases the "widget key" from the state.
# When we return back, we find that streamlit has forgotten our selection.
# So to handle that case, we use the Backup to provide for the right selection option.
# NOTE: Streamlit does not delete user created keys unlike the widget keys
#
try:
OptionDefaultIndex = GetYourOptions().index(st.session_state['YourOptionSelectButton_State_Backup'])
except:
OptionDefaultIndex = 0
else:
OptionDefaultIndex = 0
SelectedOption = st.selectbox(
'Select YourOption',
GetYourOptions(), #This call should return same sequence of items every time
index=OptionDefaultIndex,
key='YourOptionSelectButton_State'
)
st.session_state['YourOptionSelectButton_State_Backup'] = SelectedOption
return SelectedOption
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment