32  Adding a ‘Run’ Button

One simple way to control app flow is by using the st.button.

Let’s take a look at a simple simulation model.

import streamlit as st
import pandas as pd
from des_classes import g, Trial

st.title("Simple One-Step DES")

num_nurses_slider = st.slider("What is the number of nurses in the system?",
                              min_value=1, max_value=10, value=1)

sim_duration_input = st.number_input("How long should the simulation run for (minutes)?",
                                      min_value=60, max_value=480, value=120)

num_runs_input = st.number_input("How many runs of the simulation should be done?",
                                  min_value=1, max_value=100, value=5)


g.patient_inter = patient_iat_slider
g.mean_n_consult_time = patient_consult_slider
g.number_of_nurses = num_nurses_slider
g.sim_duration = sim_duration_input
g.number_of_runs = num_runs_input

############
# NEW      #
############
# A user must press a streamlit button to run the model
button_run_pressed = st.button("Run simulation")

if button_run_pressed:

    results_df = Trial().run_trial()

    st.dataframe(results_df)
############
# END NEW  #
############

Here, by creating a button with st.button and specifying that we do not run the line results_df = Trial().run_trial() until button_run_pressed is true, then we will ensure that we do not have this long-running calculation running every time a slider value is adjusted.

This would work for any code; as long as it is indented a level from if button_run_pressed then it will not execute until the button is pressed.

Tip

When a slider or other user input is next adjusted, any outputs that appeared after the button was pressed will disappear until the run button is pressed again.

32.1 Streamlit forms

An alternative to this is to use the official Streamlit forms component.

https://docs.streamlit.io/develop/api-reference/execution-flow/st.form