Persitend and responsive input widgets

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:

# for navigation"",options=["Setting responsive","Setting persistent"])

if select=="Setting responsive":
    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":"""
    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.

Hi @BenediktPrusas,

I haven’t had a chance to test your code locally yet but I wanted to pop by and see if a recent Knowledge Base article from our docs might help.

Widget updating for every second input when using session state

The key things to take away here:

  • 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.

Hopefully, this helps!

Happy Streamlit-ing!

Thank you @Marisa_Smith.

Thanks to your hint. I mangend to get the behaviour as I wanted (as long as you do not click to fast)
. You can the see my solution below, and the toy example is now on the streamlit cloud as well:

    if value not in st.session_state:

    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)
        st.number_input(label="Setting Three", on_change=update_value(value,key) ,value=st.session_state[value],key=key,step=1.0)
1 Like