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.
Thanks for stopping by! We use cookies to help us understand how you interact with our website.
By clicking “Accept all”, you consent to our use of cookies. For more information, please see our privacy policy.
Cookie settings
Strictly necessary cookies
These cookies are necessary for the website to function and cannot be switched off. They are usually only set in response to actions made by you which amount to a request for services, such as setting your privacy preferences, logging in or filling in forms.
Performance cookies
These cookies allow us to count visits and traffic sources so we can measure and improve the performance of our site. They help us understand how visitors move around the site and which pages are most frequently visited.
Functional cookies
These cookies are used to record your choices and settings, maintain your preferences over time and recognize you when you return to our website. These cookies help us to personalize our content for you and remember your preferences.
Targeting cookies
These cookies may be deployed to our site by our advertising partners to build a profile of your interest and provide you with content that is relevant to you, including showing you relevant ads on other websites.