Using st.empty()

Hi @VishnuS-S,

The reason this is happening is that when you use with ... with an empty element, you are creating a multi-element container inside of it. And, when you use it the second time, the container isn’t emptied, but instead elements in it are replaced one at a time. You can work around this by calling ph.empty() before populating it. For some reason, you also have to add a small sleep for the empty to actually work. Here’s a slightly modified version of your script that calls an empty function before replacing the container’s contents.

from time import sleep
import streamlit as st

def empty():
    ph.empty()
    sleep(0.01)

def c():
    st.session_state.b1 = True

def d():
    st.session_state.b2 = True

b1 = False
b2 = False
ph = st.empty()
if "b1" not in st.session_state:
    st.session_state.b1 = False
if "b2" not in st.session_state:
    st.session_state.b2 = False

with ph.container():
    st.write("Page 1")
    b1 = st.button("Page 2", on_click=c)

if st.session_state.b1 or b1:
    empty()
    with ph.container():
        st.write("Page 2")
        st.write("Page 2 contents")
        b2 = st.button("Page 3", on_click=d)

if (st.session_state.b2 or b2) is True:
    empty()
    with ph.container():
        st.write("Page 3")
1 Like