Button with > 1 `on_click` calls / functions?

I am using a button with on_click calling a function. That function is quite large, and I want to refactor it, but that would mean needing multiple on_click calls, to run in sequence.

Is there any way to do this? Thanks :slight_smile:

You can call on_click multiple times in sequence by clicking the button multiple times but I don’t think that is what you want.

A common approach to refactor a too large function is extracting other functions. That way the function looks the same from the outside but its body becomes shorter and (hopefully) more readable.

2 Likes

@altanner The method @Goyo suggests is exactly right. Here’s a concrete example of what that could look like in your app

import streamlit as st


def callback1():
    st.write("Callback 1")


def callback2():
    st.write("Callback 2")


def callback3():
    st.write("Callback 3")


def master_callback():
    callback1()
    callback2()
    callback3()


st.button("Run callbacks", on_click=master_callback)
2 Likes

OK cool, I had suspected this: thanks for confirming that that approach isn’t too crazy!

Just need to figure out what is worth chopping up or not :slight_smile:

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