Hi, is there a way to stop screen refresh after an user clicks a button? I would like to display the output from clicking the button without refreshing the screen. Currently, it refreshes the screen and displays from the start. Thanks.
Short answer is no, but…
-
There is a stop button in the upper-right corner that can do this. There just isn’t a way to make an
st.button
do the same thing without triggering a rerun. -
There is a sort of edge case with fragments. When a fragment writes outside of its main container, the writes are accumulative. So you could have a fragment running which writes to some other container and have a button in the fragment to stop it. However, when I put together a code sample, it did something unexpected so now I’m reporting a bug…
Thanks for the comment. I searched the forum and found some older discussions. I couldn’t figure out the status. So thank you very much for clearing it up.
Isn’t this a serious issue to resolve? If I don’t want to refresh the screen when a button is clicked, does that mean I cannot use streamlit?
An engineer helped clean up my fragment example to work. It’s kind of limited because you have create a list of the things you want to display and have a fragment iterate through them to display one at a time. (A fragment can’t be interrupted in the middle of a run, so you have to break it up to do one thing at a time.)
import streamlit as st
import time
if "items" not in st.session_state:
st.session_state.items = range(50)
if "i" not in st.session_state:
st.session_state.i = 0
if "run" not in st.session_state:
st.session_state.run = False
def run():
st.session_state.run = True
@st.fragment()
def frag_writer(container):
st.button("Start", on_click=run)
st.button("Stop", on_click=st.stop)
if st.session_state.run and st.session_state.i < len(st.session_state["items"]):
container.write(st.session_state["items"][st.session_state.i])
st.session_state.i += 1
time.sleep(.2)
st.rerun(scope="fragment")
else:
st.session_state.run = False
header = st.container()
body = st.container()
with header:
frag_writer(body)
This example will write through the list, where you can start and stop it. You’d need to trigger a full-script rerun to clear the page.