Changing the Widget's Value

Hey everyone,

I would like to change the value of a number_input widget later on. In my case, I ask for user input first:

D = st.number_input("Diameter", value = 6.0)

Also, I give user the option to calculate the D using some other method. However, when user uses this method, I want to change the displayed value of Diameter widget above. I connect this other method with a button so,

# other method to calculate the value of D
button_D = st.button("Use other method")
if button_D:
   #change the current value of D displayed to user.

You can find an example here:
Streamlit Snippets · Streamlit

Hi Berk!

One easy way to set the widget value based on some later logic is to use st.empty() as a placeholder for the original st.number_input. Here’s an example that lets the button click override the value of the number_input to 5:

https://share.streamlit.io/akrolsmir/streamlit-snippet/main?snippet_id=MwNFR514

Hope that helps! And thanks for using Streamlit Snippets to show us your code example :wink:

1 Like

I wasn’t aware of this usage and I still can’t understand how it works, but it works! I will dig into it. Thank you.
Edit: Wow that can be used as a placeholder! I needed that in long codes to calculate the value later on, but I couldn’t manage! Thank you x 2.

Can you please check this behaviour? After clicking the button, if I change it manually, it resets to initial value we have given to code. Is there any way to block this? Because user may think they entered the value, but code will change it automatically. If they try twice, it works.

Try here: Streamlit Snippets · Streamlit

Oh, you’ve run into one weird thing about buttons – they don’t do a great job of keeping track of state, because when the script reruns (aka when you update the number input), the button resets to false, which then causes the number_input to also reset to 10.

You can solve this with a radio button instead, since radio buttons persist on reruns. Try this:

https://share.streamlit.io/akrolsmir/streamlit-snippet/main?snippet_id=TTzOReS_

I understand the solution, but button would be better user experience. However, I cannot find the logic why it works in second time. If user enters the value twice, it takes at second and other times.
Streamlit Snippets · Streamlit