I’m having the main page perform some predictions. But every time I go to a different page while it is not complete and return back, I get an error and have to refresh the entire page. Is there a way to just disable page navigation until the loading process is completed?
Here is a sample demo on how this can be done. There can be other ways. In this demo there is a selectbox in the sidebar that we want to disable if we run a prediction.
A selectbox has a disabled parameter, we can use it to enable/disable this box. Create a callback function in the prediction button to disable the selectbox in the sidebar. We also need a variable to handle selectbox disability.
import time
import streamlit as st
if 'selboxdisabled' not in st.session_state:
st.session_state.selboxdisabled = False
def cb():
"""Disables sidebar selectbox.
A callback function to be executed when prediction
button is pressed or triggered.
"""
st.session_state.selboxdisabled = True
def run_prediction(sec):
time.sleep(sec)
return 'done'
st.sidebar.selectbox('select name',
['', 'roel', 'alex', 'allan'],
disabled=st.session_state.selboxdisabled)
run = st.button('do prediction', on_click=cb)
if run:
status = run_prediction(5)
# Restore selboxdisabled state.
if status == 'done':
st.success('prediction is done')
st.session_state.selboxdisabled = False
# Call rerun so that streamlit will rerun the code
# from top to bottom thereby hitting the statement:
# st.sidebar.selectbox(...)
# but now with st.session_state.selboxdisabled set to False.
# As a result the sidebar selectbox will be enabled again.
st.experimental_rerun()