St.button on_click is called when page refresh

Every time I refresh page, “aaa” and “bbb” will be printed.
I hope they could only be printed after I press button.
following is my code:

def pp(v):
    st.write(v);
if(add_selectbox=="button") :
    bt1=st.button("test1", key=None, help="help info", on_click=pp("aaa"), args="ccc", kwargs=None, disabled=False)
    bt2=st.button("test2", key=None, help="help info", on_click=pp("bbb"), args="ddd", kwargs=None, disabled=False)

Hi @wocat11 :wave:

If you want the callback to execute on click, pass the function name to the on_click parameter instead of a function call with arguments. Here’s a working example:

Code

import streamlit as st

def pp(v):
    st.write(v)

bt1 = st.button(
    "test1",
    key=None,
    help="help info",
    on_click=pp,
    args=("aaa",),
    kwargs=None,
    disabled=False,
)
bt2 = st.button(
    "test2",
    key=None,
    help="help info",
    on_click=pp,
    args=("bbb",),
    kwargs=None,
    disabled=False,
)

Output

button-onclick

Perhaps we should an example of how to use buttons with callbacks to the docs? :thinking:

1 Like

Thank you very much! And more example will be useful for us :grinning:

1 Like