How to select a function with a checkbox and run it using a button in Streamlit?

I am designing a Streamlit app that allows to select a function or functions using checkboxes and then execute that function(s) using a button. I am using Python 3.10.4, Streamlit 1.11.1, Virtualenv, Windows 11, Firefox 103.0.1 (64-bit). There are two checkboxes that allow to choose two different functions.

My problem is that I am unable to run the functions by clicking the button. Instead the functions are executed once their respective checkbox is checked. This is due to the if condition in the functions, without which the functions are automatically executed. I have tried to use the on_change parameter for the checkbox, but this executes the associated function when the checkbox is checked.

I would like to know how I can use the checkbox(s) to select the function and then execute it using the the button. Any form of help would be appreciated.

The code is shown here:

import streamlit as st


# Function 1
def func1():
    if cb1:
        st.write("Function 1 executed.")


# Function 2
def func2():
    if cb2:
        st.write("Function 2 executed.")


# function to run chosen function(s)
def execute():
    func1()
    func2()


# sidebar configurations
cb1 = st.sidebar.checkbox('Function 1', key='a')
cb2 = st.sidebar.checkbox('Function 2', key='b')
run_btn = st.sidebar.button('Run', on_click=execute(), key='c')

The on_click kwarg in st.button is a callable, so you only need to pass execute, not execute().

But also, imo it’d be more readable to keep the conditionals only in the execute function, something like this:

import streamlit as st

def func1(): st.write("Function 1 executed.")
def func2(): st.write("Function 2 executed.")

# Function to run chosen function(s)
def execute():
    if cb1: func1()
    if cb2: func2()

# Sidebar configurations
cb1 = st.sidebar.checkbox('Function 1', key='a')
cb2 = st.sidebar.checkbox('Function 2', key='b')
run_btn = st.sidebar.button('Run', on_click=execute, key='c')

This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.