Click twice on button for changing state

if st.button('Back'):
    st.session_state.page = ""

When you have a snippet like this.

  1. The user clicks the button
  2. The script reruns
  3. The button is True and the conditional code executes
  4. The script ends

It’s not until the script reruns again that the new value of st.session_state.page will be reflected at the top of the script where you need it to correctly logic gate your code.

Option 1: Add st.experimental_rerun()

You can cause a second rerun to happen by adding st.experimental_rerun() after any line changing the value of st.session_state.page

if st.button('Back'):
    st.session_state.page = ""
    st.experimental_rerun()

Option 2: Use a callback

If you want the button to set the page before the script reruns, you can use a callback.

import streamlit as st

if 'page' not in st.session_state:
    st.session_state.page = 'home'

def set_page(page):
    st.session_state.page = page

st.write(f'The page is {st.session_state.page}')

st.button('Home', on_click=set_page, args=['home'])
st.button('Edit', on_click=set_page, args=['edit'])
st.button('Create', on_click=set_page, args=['create'])


st.write(f'The page is {st.session_state.page}')
2 Likes