Functions not running

If you’re creating a debugging post, please include the following info:

  1. running locally,
  2. no public link
  3. N/A
  4. N/A
  5. python 3.12.3 , streamlit 1.35.0

this code should call a function every time a button is clicked to toggle session_state.clicked between true and false
it runs once, but doesn’t run when called again. Any ideas why this is responding in this manner?

import streamlit as st

if 'clicked' not in st.session_state:
    st.session_state['clicked'] = False  # clicked initialized to False

def click(): # this should toggle clicked between True and False
    if st.session_state.clicked == False:
        st.session_state.clicked = True
    else:
        st.session_state.clicked = False
st.session_state # monitor session state
st.button("num1",key='num3', on_click=click)
if st.session_state.clicked:
    st.write("in if 1")
    click()
st.button("num2",key='num2', on_click=click)
if st.session_state.clicked:
    st.write("in if 2")
    click()

It can help if you add a little more debugging, specifically you can add st.write("IN CLICK") inside the click function – the basic answer is because “click” ends up being called twice (once because of the on_click, and then once again because you’re checking to see if it’s now True with your two if statements), and so it toggles it from false to true, then back to false, and it ends up back where it started.

I’m not sure exactly what you’re trying to accomplish, but here’s a simplified version of your script that just calls “click” when a button is clicked, so it only gets called once per run instead of twice

import streamlit as st

if "clicked" not in st.session_state:
    st.session_state["clicked"] = False  # clicked initialized to False


def click():
    st.session_state["clicked"] = not st.session_state["clicked"]


st.write("Now st.session_state.clicked:", st.session_state.clicked)

st.button("num1", key="num3", on_click=click)
st.button("num2", key="num2", on_click=click)

st.write("Now st.session_state.clicked:", st.session_state.clicked)