Home > Software engineering >  on_click function assigned to Streamlit button runs before the click event
on_click function assigned to Streamlit button runs before the click event

Time:08-09

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 enter image description here

CodePudding user response:

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) 

CodePudding user response:

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

  • Related