Buttons running a on-click function during startup and runtime

Hi all,

I am making a Streamlit app for simple permission management of an SQL database.

In this app I have some functions doing SQL queries (adding and deleting rows in the database) when a button is pressed. Problem is these buttons execute my add/remove functions at startup and during runtime. This should only be done when performed by the user!

Example button and function.
userID is picked from a st.selectbox
df is generated from a st.multiselect list

def update_Usergroup(userID, df):
    eng = makeConnection() # sqlalchemy create engine function

    st.success('update_Usergroup is run')    

    query = f"""DELETE FROM Users_Usergroups_Comb
    WHERE UserID = {userID};
    # write to Users_Usergroups_Comb table with no index and appending the dataframe to the DB
    df.to_sql('Users_Usergroups_Comb',con=eng, index = False, if_exists = 'append')


st.button('Save updated usersgroups', on_click = update_Usergroup(userID, membership))

How can I control the app such that on_click is not executed automatically?

Thanks in advance!


Try replacing your st.button statement with the following code:

if st.button(‘Save updated usersgroups’):
update_Usergroup(userID, membership)