Last active
February 23, 2025 09:42
-
-
Save skannan-maf/c526859afde60b27388a8ecddd051840 to your computer and use it in GitHub Desktop.
Streamlit selectbox that works as intended
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # | |
| # This gist solves 2 problems | |
| # 1. Streamlit selectbox sometimes does not return correct value correpsonding to what user selected. | |
| # This is a very finicky behavior where the user-selected option, occasionally, reverts back to older option | |
| # and thus violating WYSIWYG. This function fixed it | |
| # 2. In multi-page apps, the user-selected values in selectbox gets lost when user switches to another page. | |
| # This function saves the state and helps these widget maintain state even in multi-page apps | |
| # | |
| def stateful_selectbox( | |
| name, | |
| dropdown_options, | |
| widget_key, | |
| default_index=0 | |
| ): | |
| twin_key = widget_key + '_twin' #User variables (like ..._twin) are not lost when switching pages whereas widget keys are lost | |
| selected_index = default_index | |
| if widget_key not in st.session_state: | |
| if twin_key in st.session_state: | |
| # This condition happens when the user has returned back after visiting a new page | |
| widget_value = st.session_state[twin_key] | |
| #st.session_state[widget_key] = widget_value #FIX: This will be set by the st.selectbox() call below | |
| try: | |
| selected_index = dropdown_options.index(widget_value) | |
| except: | |
| selected_index = 0 | |
| del st.session_state[twin_key] | |
| else: | |
| assert twin_key in st.session_state | |
| widget_value = st.session_state[widget_key] | |
| del st.session_state[widget_key] | |
| try: | |
| selected_index = dropdown_options.index(widget_value) | |
| except: | |
| selected_index = 0 | |
| #st.write('selectbox called with options={} key={} index={}'.format(dropdown_options, widget_key, selected_index)) | |
| widget_value = st.selectbox( | |
| name, | |
| options=dropdown_options, | |
| key=widget_key, | |
| index=selected_index | |
| ) | |
| st.session_state[twin_key] = widget_value | |
| return widget_value |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment