Button on_click behavior

I have a button with an on_click() to run a function which executes a query. It seems the on_click() is triggered when the parameters change, even if the button is not clicked. Example below - when queryText is changed via a text_area control, the on_click() function is executed.

 queryText = st.sidebar.text_area("SQL to execute:", value="", height=3, max_chars=None )     
    if queryText:                     
        # issue - on_click executes when queryText is changed  , even if not clicked
        btnResult= st.sidebar.button('Run', key='RunBtn', help=None, on_click=runQuery(queryText,False), args=None, kwargs=None)
        if btnResult:
            st.sidebar.text('Button pushed')

Hi @MarkSim.,

Based on your simplified example I don’t think you should use state for this. I actually think you just need to use a form, that collects the SQL query and then has a form_submit_button that runs the typed query:

with st.sidebar.form("Input"):
    queryText = st.text_area("SQL to execute:", height=3, max_chars=None)
    btnResult = st.form_submit_button('Run')

if btnResult:
    st.sidebar.text('Button pushed')

    # run query
    st.write(queryText)

In my token example, I simply write the query to the page but you would be able to actually send the queryText to get the data.

Let me know if this solves your issue!
Happy Streamlit-ing
Marisa

1 Like

Hey marduk,

I don’t know why on_click of all buttons will be executed. but you may try more simple snippet.

import streamlit as st

st.title(‘Select a soccer player’)

option=st.selectbox(
‘Choose a player you like:’,
(’-’,‘Messi’,‘Ronaldo’),index=0,key=‘option’)

st.metric(‘Selected Player’,value=option)

Hey marduk,

I found below codes work for you. And also found you had deleted your post.

Did you get the answer? And any finding from you?

import streamlit as st

st.title(‘Select a soccer player’)

if ‘player_name’ not in st.session_state:

st.session_state.player_name=’-’

def selectplayer(player):

st.session_state.player_name=player

st.metric(‘Selected Player’,value=st.session_state.player_name)

st.button(‘Messi’,on_click=selectplayer,args=(‘Messi’,))

st.button(‘Ronaldo’,on_click=selectplayer,args=(‘Ronaldo’,))

从 Windows ç‰ˆé‚źä»¶ć‘é€

2 Likes

Thanks @kegui for sharing! Indeed you have to use the args argument to pass any arguments to the on_click. Otherwise all buttons will run.

1 Like

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