Setting widget values using session_state does not work after initialization

Hello, Guys.
I need a little help.

I using session_state to store values of a slider and a callback function assigned to a button change it’s value later, just like the snippet from this article:

def plus_one():
    if st.session_state["slider"] < 10:
        st.session_state.slider += 1

add_one = st.button("Add one to the slider", on_click=plus_one, key="add_one")
slide_val = st.slider("Pick a number", 0, 10, key="slider")

My problem is that i need to be able to call plus_one after, without the button.
When I simply call the function inside my code, I got an error:
**StreamlitAPIException** : st.session_state.slidercannot be modified after the widget with keyslider is instantiated.

Is there a way I update the slider value without getting this error?

Because streamlit code executes from top to bottom, being able to set a widget value after it is initialised wouldn’t make a lot of sense. The widget’s function return occurs when it is called, so being able to set its value later would be confusing.

One solution is to call your function before the widget is initialised.

Otherwise, if what you want is for the slider to be set to a value for the next run of the script, you must still set it before the widget is initialised. One way to do that is with a new variable in st.session_state which lets the next run know it needs to change the value of the widget. For example:

#initialise slider in st.session_state
if 'slider' not in st.session_state:
    st.session_state['slider'] = 0

if 'add_one' in st.session_state:
    if st.session_state['add_one']:
        if st.session_state['slider'] < 10:
            st.session_state.slider += 1
        st.session_state['add_one'] = False #so this code does not execute next run

slide_val = st.slider("Pick a number", 0, 10, key="slider")

if st.button("Add one to the slider"):
    st.session_state['add_one'] = True

Hello, thanks for your help!

What I’m trying to achieve it’s like a “two way binding” between the widget value and another function down in the code. My script is processing videos and I`m using the slider to set the actual frame, but, if a play button is pressed, the script enters in a while True block that iterates over the video. And this “while” block should be able to increment the slider value with:

st.session_state['slider'] += 1. This code returns error. I tried to call the “plus_one” function instead, but with the same error.

To my knowledge this isn’t possible. I believe the value of a widget can only be set once each time the code is run.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.