on_click function assigned to Streamlit button runs before the click event in browser

Viewed 63

I am trying to run a script in streamlit button with onclick="" parameter. Problem is, the script start running before even button shows up on the browser. Any idea what maybe the mistake here?

import streamlit as st
from level_packs import create_packs
st.set_page_config(page_title="Main work", page_icon="")

st.markdown("# Main work")

st.button('Run script', on_click=create_packs())
2 Answers

You could initialize a session state for the button and pass the function to an if statement.
Something like:

runbtn = st.button('Run script')

if "runbtn_state" not in st.session_state:
    st.session_state.runbtn_state = False

if runbtn or st.session_state.runbtn_state:
   st.session_state.runbtn_state = True
   create_packs() # Your function

I tried with below code and its working :)

import streamlit as st

from level_packs import create_packs as f

st.set_page_config(page_title="Main work", page_icon="")


st.markdown("# Main work")


def run_button():
    st.button('Run script', on_click=f)


run_button()
Related