How should st.rerun() behave?

This is one of the surprising behaviours of st.rerun() instantly re-running the script.

st.button returns whether the button is pressed on the previous script run. When it is pressed, the script is re-run, the function returns True and, in at the end of the run, the state of the button is set to False. When another widget is altered, the script is re-run and the function returns False (because the button wasn’t pressed last run).

When st.rerun() is triggered by a button, the script never gets to finish and the button’s state never gets reset to False, so st.rerun() is executed over and over again.

If you must use st.rerun(), a workaround is to give the button a key then delete its entry from st.session_state. Even though you can’t set the st.session_state value of a button, deleting it seems to work. Try:

    with st.container():
        button = st.button("Press Me!",key = 'button')
        if button:
            logger.info("Pressed")
            st.session_state['table'] = update_table()
            del st.session_state['button']

            # ensure table redraws before running rest of script
            st.rerun()
4 Likes