Summary
New to streamlit here and enjoying it. I’m hoping someone could explain button logic for me, and the differences between using callbacks
vs the if button_pressed
idioms.
In short, under my beginner reading of the tutorial, after a button press the entire script is re-run, and so I expected the two idioms to behave differently. However, if I implement a counter using the two different idioms, I find that the if button_pressed
idiom leaves any references to the counter variable before the button press (printed out in the example below) lagging behind. For my application this is undesirable, as I would like the variable to be consistent throughout the entire page. (To be precise, I am actually using a form_submit_button, which has the same behavior as the minimal example below)
So I know what I need to do to get my desired behavior, but was wondering if someone could explain the flow of logic for me, why the two versions below differ, and how experimental_rerun()
fixes things (which I have also verified)
Thanks!
Steps to reproduce
Version 1, lagged behavior:
import streamlit as st
if "x" not in st.session_state:
st.session_state["x"] = 1
st.session_state.x
def add():
st.session_state.x += 1
st.session_state.x
submitted = st.button("Submit")
if submitted:
st.session_state.x += 1
#st.experimental_rerun() # Adding this line gives the same behavior as using callback
st.session_state.x
behavior (lagged behavior):
0
[button]
1
Version 2:
import streamlit as st
if "x" not in st.session_state:
st.session_state["x"] = 1
st.session_state.x
def add():
st.session_state.x += 1
st.session_state.x
submitted = st.button("Submit",on_click=add)
st.session_state.x
Behavior: (desired)
1
[button]
1
- Streamlit version: 1.20.0
- Python version: 3.9.13
- Using Conda
- OS version: MacOS
- Browser version: chrome