Created
December 14, 2021 15:30
-
-
Save asehmi/3bd3ee974edcd2af772b495276ce4f3f to your computer and use it in GitHub Desktop.
Maintaining widget state across a multi-page Streamlit app
This file contains 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
# Since widgets are created anew on each page their values will be initialized to their default values. | |
# I’ve created a separate ‘value cache’ to store values between pages. | |
# (Note, when a widget has a key and you initialize its value with a session state key value other than the widget’s own key value, | |
# Streamlit will complain. Therefore, the widgets don't have a key.) | |
import streamlit as st | |
# Instantiate the Session State Variables | |
if 'cache' not in st.session_state: | |
st.session_state.cache = {'name': '', 'age': '', 'gender': ''} | |
# Sidebar Widgets | |
sidebar_Title = st.sidebar.markdown('# Streamlit') | |
sidebar_pages = st.sidebar.radio('Menu', ['Page 1', 'Page 2', 'Page 3']) | |
# Page 1 | |
def page1(): | |
st.session_state.cache['name'] = st.text_input('What is your name?', value=st.session_state.cache['name']) | |
# Page 2 | |
def page2(): | |
st.session_state.cache['age'] = st.text_input('What is your age?', value=st.session_state.cache['age']) | |
# Page 3 | |
def page3(): | |
st.session_state.cache['gender'] = st.text_input('What is your gender?', value=st.session_state.cache['gender']) | |
# Navigate through pages | |
if sidebar_pages == 'Page 1': | |
page1() | |
elif sidebar_pages == 'Page 2': | |
page2() | |
else: | |
page3() | |
st.write(st.session_state.cache) |
Author
asehmi
commented
Apr 19, 2022
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment