On_Click Function Assigned to Streamlit Button Runs Before the Click Event

I’ve assigned an on_funtion to a button .Which is supposed to run a python file and start capturing the webcam. It should only be started when the button is clicked . But whenever i run the streamlit server the function runs and start capturing without a click event. The same thing happens to a form I've made also which is leading to empty data written to google sheets.

Here is the code:

import subprocess
import sys
import streamlit as st
from activity_check import high_count
act_lev = ""
def start_capture():
    subprocess.run([f"{sys.executable}", "activity_check.py"])
def run_cap():
    st.button("Start Capturing",on_click=start_capture)
run_cap()
st.write(high_count)

The function should start only when i click, but its executing automatically

I thought a gif would help

3 Answers

this is a way to solve it:

    import subprocess
    import sys
    import streamlit as st

    from activity_check import high_count
    act_lev = ""

    def start_capture():
        subprocess.run([f"{sys.executable}", "activity_check.py"])

    if st.button("Start Capturing"):
        st.write(start_capture())

    st.write(high_count)

Try making your button conditional.

import subprocess
import sys
import streamlit as st
from activity_check import high_count
act_lev = ""


def start_capture():
    subprocess.run([f"{sys.executable}", "activity_check.py"])


def run_cap():
    cap_button = st.button("Start Capturing") # Give button a variable name
    if cap_button: # Make button a condition.
        start_capture()
        st.text("Captured Successfully")
 
run_cap()
st.write(high_count) 
6

The reason is because i i've imported this variable

**from activity_check import high_count**

when i removed it. It started working as normal. Now i've to figure out a way to get the value of that variable somehow.

Anyway case closed

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Elena Rostova

Elena Rostova

Lead Health, Wellness & Medical Journalist

Elena Rostova holds a Master's degree in Public Health Journalism. She covers groundbreaking medical research, holistic wellness trends, mental health awareness, and nutritional science.

Share this article
Twitter Facebook Pinterest