I think its easiest to understand the question if you test the code snippet below.
You will notice that the first input widget behaves responsive, but restores to default vaule if you hide it and render again.
The second input widget keeps it vaule if you, re-render it, but only changes the value every 2nd attempt to change it.
But how do i get an input widget, which can keep it’s value but behaves responsive?
import streamlit as st
# Initialise Session Sate
if "value_two" not in st.session_state:
st.session_state["value_two"]=20
# for navigation
select=st.radio(label="",options=["Setting responsive","Setting persistent"])
if select=="Setting responsive":
st.warning("""
Good: Changing values behaves as expected
Bad: If you switch to the other settings and back, all values will be restored to default""")
st.session_state["value_one"]=st.number_input(label="Setting One",value=20,key="Key One")
if select == "Setting persistent":
st.info("""
Good: If you switch to the other Settings and back those values will stay the same
Bad: Try changeing the same value multiple times in sucession. You will notice it changes only every other time""")
st.session_state["value_two"]=st.number_input(label="Setting Two",value=st.session_state["value_two"],key= "Key Two")
Related, but the proposed solution of @ksxx leads to the resoreing to default behaviour.
use a call-back function to update your app’s variable before the script re-runs
make sure you’re using the values stored in your session state and not the return values of widgets
specifically in your case:
You’re assigning a key directly to a number input, creating the number input on a different line and adding it to session state with a key. Then in your call back set your value_one to the number inputs value.
if value not in st.session_state:
st.session_state[value]=default_value
def update_value(value,key):
st.session_state[value] = st.session_state[key]
if key not in st.session_state:
st.number_input(label="Setting Three", value=st.session_state[value], key=key,step=1.0)
else:
st.number_input(label="Setting Three", on_change=update_value(value,key) ,value=st.session_state[value],key=key,step=1.0)