Streamlit reruns a script every time an action occurs: a button is pressed, a number is input, etc. To save a value, use a cached function to maintain values between runs.
I'm pretty sure this is what you want:
import streamlit as st
# Keep the state of the button press between actions
@st.cache_resource
def button_states():
return {"pressed": None}
press_button = st.button("Press it Now!")
is_pressed = button_states() # gets our cached dictionary
if press_button:
# any changes need to be performed in place
is_pressed.update({"pressed": True})
if is_pressed["pressed"]: # saved between sessions
th = st.number_input("Please enter the values from 0 - 10")
Note: you said you wanted a slider, but then you used a number input. If you actually wanted a number slider, use
st.slider("Select a Number", min_value=1, max_value=10, step=1)
A few extra things to consider:
- If you want the number input to guaranteed appear directly beneath the button, you will need to create a place holder near the top of your script:
btn = st.empty()
nmb = st.empty()
This guarantees that nmb
will appear directly beneath btn
. And when you define your widgets, instead of calling st.button(...)
you call btn.button(...)
.
- If you want to create a toggle button (when you click it again, the number input disappears), you can do so by using
if press_button:
is_pressed.update({"pressed": not is_pressed["pressed"]})
- If you want the button to disappear after you press it, use
if is_pressed["pressed"]:f
btn.empty()
th = nmb.number_input(...)