How can I get a button that resets its state each run?

I’m using the st.button to trigger the execution of a job in databricks. The problem is that the button built into streamlit returns a value of TRUE based on if the button was clicked on the last run of the script. This means that whenever I launch the script, it automatically runs the trigger even though I haven’t clicked on the button.

How can I get the button to reset itself right after its been clicked each time? I want the button to only activate when someone clicks it and resets its state right after

Hi @Anaqi_Afendi,

First, welcome to the Streamlit community!! :partying_face: :tada: :partying_face: :star2: :partying_face: :tada: :partying_face: :star2:

I’m not sure I follow your issue because that is how the button works. :thinking:

On the first run of your script, it would render all of your buttons/widgets etc… and the value of the button would be False. On detecting that the button is pressed streamlit will re-run the script from the top (just once) and then the button value returns to False.

Can you mock up a MWE (minimum working example) that shows this unexpected behaviour? Also if you can tell me your streamlit version as well!

Happy Streamlit-ing!
Marisa

3 Likes

Hi Anaki, Marisa, :wave:

Alternatively you may want to assign st.button to a variable (button1) and control the app flow via st.stop()

e.g.

if not button1:
    st.stop()
else:
    #the action you want

Would that work?

Best,
Charly

3 Likes

Thanks for the respone! I’ve been able to fix my problem using the session states, I’m guessing this is the best way to do it?

What I wanted originally is to have a button that will trigger a job, but that button should stay in the False state until it is clicked. Once it is clicked, it will trigger the job, but only once and never again.

I’m not able to get a proper MWE of the example but this as close as I can get:

from Streamlit.Entity_Resolution import prepare_sample
import streamlit as st
import Triggers.Run_Prep_to_Samples

st.write('On startup, button state should be false')

if st.button('button'):
    Triggers.Run_Prep_to_Samples

# Some other buttons and widgets 

Streamlit version: 0.84.1

The trigger I only want to run once. I suspect because of the way it is imported it runs the trigger right off the bat even though the button state might be False. I read somewhere in the documentation that streamlit re-runs the script from top to bottom each time a widget is changed and so this can explain why this implementation of the button would result in constant triggering.

Thanks for the suggestion Charly!

What does st.stop do exactly?

1 Like

You’re welcome.

It stops the script’s execution.

Best,
Charly

1 Like