Button inside button is resetting the page
Summary
I have a scenario where, when a button is pressed, it should perform some action and then a new button should appear for further actions. But, when the new button is pressed, the current page is getting completely reset. Sample code as shown below,
if st.button("Button 1"):
st.text("Button 1 pressed")
if st.button("Button 2"):
st.text("Button 2 pressed")
Steps to reproduce
With the above-mentioned code snippet,
- Click on 'Button 1'
- Displays message "Button 1 pressed" and Button 2 appears
- Press 'Button 2' to reproduce the bug
Expected behavior:
When 'Button 2' is pressed, the page should maintain previous information and execute further actions.
Actual behavior:
The complete page is getting reset.
Is this a regression?
No
Debug info
- Streamlit version: 0.52.2
- Python version: 3.7.5
- Using Conda
- OS version: MacOS 10.14.6
This is working as streamlit was designed, the code reruns from top to bottom after every action, in that new run it will only have access to the latest action. In your example after pushing button 2 it doesn remember pushing button 1 before that.
I guess you could do a ugly workaround like so:
if st.button("Button 1") | st.button("Button 2"):
st.text("Button 1 pressed")
if st.button("Button 2"):
st.text("Button 2 pressed")
If you dont have too many steps in your button trail :)
Thanks for the clarification.
I guess, above workaround is not working. Getting DuplicateWidgetID: There are multiple identical st.button widgets with the same generated key. error.
Anyways, got your point :)
I know the topic is closed but here is a functional workaround to this issue:
import SessionState
button1 = st.empty()
text1 = st.empty()
button2 = st.empty()
text2 = st.empty()
ss = SessionState.get(button1 = False)
if button1.button('1') or ss.button2:
ss.button1 = True
if ss.button1:
text1.write('you clicked the first button')
if button2.button('2'):
text2.write('you clicked the second button')
Hello all, I know the topic is closed but I have tried all the workarounds in this issue and none of them works.
Here is a solution that worked for me :