St.number_input behavior

Hi,

I am having an issue with st.number_input. Here is an example of my code:

def update_change():
    update_database(st.session_state.myvar)

#IN main code body
st.session_state.myvar = st.number_input("Enter Number",min_value=0.0,max_value=1.0,value=st.session_state.myvar,on_change=update_change,label_visibility="collapsed")

When I change the value in the number_input and press enter, it calls the on_change function but it does not change st.session_state.myvar.
Why is this happening?

When you change the value of a widget, the callback will execute before the script reruns and outputs the new value. Since you assign the value through the output of the widget function, it won’t get updated until after the callback completes.

Instead, use “myvar” as the key for your widget.

def update_change():
    update_database(st.session_state.myvar)

#IN main code body
st.number_input("Enter Number",min_value=0.0,max_value=1.0,key="myvar",on_change=update_change,label_visibility="collapsed")

If you don’t manually initialize the value in Session State, it will get initialized with a value of 0 when the widget function is executed. If you want to force a default value, add to your script before the widget:

if "myvar" not in st.session_state:
    st.session_state.myvar = .5 # Or whatever starting value you want

Note: if you want to carry this value to other pages in your app, some extra steps will be needed. When you navigate away from a widget, its associated key in Session State will get deleted. To learn more about widget behavior (including the specifics of callbacks, keys, and multipage implications, check out Widget behavior in the docs.

the solution works!!

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