One st.button only work on double click

I have this section of my code that stopped working for some reason

    st.divider()
    st.text("debug add button")
    if st.button(":material/add:", key="create_new_dv"):
        print("debug button add")
        st.write("debug button add pressed")
        # create_dataviz(project)


@clean_dialog("New dataviz", "__new_dv_dialog_")
def create_dataviz(project: Project):
    ...

last time I’ve checked I could use this button to open the create_dataviz dialog, but now when I click on it… I see a rerun then nothing, like it stays on False, so I put some debugging print, thinking that the issue was in my dialog but no, even the print is not going through.
I saw that double-clicking the button does open the dialog though (and do the debug prints). So this button only works on double click…

Sure enough I copy pasted my code to make a minimal example, but it works as intended, likewise, I have pretty much the same system in another tab of my code and it works as intended, first time, in the same run.

Obviously I don’t think I gave enough information for you to be able to debug it but also idk how to reproduce it, my code is pretty big and I couldn’t reproduce it… if you have any pointers on how to debug this I could try.

Hmmm, I’m not entirely sure, but a couple thoughts:

  • The key helps the value of the button store as a session state (st.session_state.create_new_dv), is that somehow being cleared when the code reruns? Maybe it’s reassigned somewhere or all session states are cleared or something like that
  • I’m a big proponent of always using callbacks with streamlit widgets, rather than if statements. That way the callback code (in this case you could put the print & st.write in the callback) runs immediately after the button push and reduces any chance that weird things happen due to the entire code rerunning before the if statement is reached

try this

st.button(":material/add:", key="create_new_dv", on_click=create_dataviz, args=(project))

@clean_dialog("New dataviz", "__new_dv_dialog_")
def create_dataviz(project: Project):

Yeah, you’re right, using a callback fixed the issue, this seems more reliable. Thank you very much, both of you.

2 Likes

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