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};
    """
    eng.execute(sa_text(query).execution_options(autocommit=True))
    # 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')

return

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!

Hi @EBEN

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

if st.button(โ€˜Save updated usersgroupsโ€™):
update_Usergroup(userID, membership)

Hi @EBEN,

I know that your post is half a year old, however my answer might also help others. The behavior you see is caused by how you define the callback. Change
st.button('Save updated usersgroups', on_click = update_Usergroup(userID, membership))
to
st.button('Save updated usersgroups', on_click = update_Usergroup, args = (userID, membership))
and you are all good.

Note: In case one is setting up a callback function that needs just a single string parameter, passing it like args = ("foobar") wonโ€™t work, as this will pass each string character individually, causing an โ€œ6 parameters passed, but 1 parameter expectedโ€ exception. Use args = ("foobar", ) as workaround.

2 Likes

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