How to trigger st.experimental_dialog with On Click Function?

I’m using an on_click function to trigger a dialog.

However, I receive an error message when I click on the close button.

The following script displays three buttons.

The third button produces an error when closing the dialog.

RuntimeError: Could not find fragment with id 1c78f2182f4bcfbd2cda9b9971306dc7
Traceback:
File "/home/user/streamlit_fragment_test/.venv/lib/python3.8/site-packages/streamlit/runtime/scriptrunner/script_runner.py", line 595, in _run_script
    raise RuntimeError(

My script:

import streamlit as st


def simple_on_click_function(key):
    st.write("You clicked me", st.session_state[key])
    if st.button("Close"):
        st.rerun()


@st.experimental_dialog("You clicked a button!")
def show_dialog(key):
    st.write("You clicked me", st.session_state[key])
    if st.button("Close"):
        print("closing!")
        st.rerun()


def run_full_script():
    st.divider()
    st.write(
        "Clicking Button 1 triggers a simple on-click function to display some text.")
    st.write("Cicking the close button works as expected.")
    st.button("Button 1 - Simple On Click Function", key="button_1",
              on_click=simple_on_click_function, args=["button_1"])

    st.divider()
    st.write("Clicking Button 2 triggers a dialog function to display some text.")
    st.write("Clicking the close button in the dialog works as expected.")
    if st.button("Button 2 - Show Dialog - No Error", key="button_2"):
        show_dialog("button_2")

    st.divider()
    st.write("Clicking Button 3 triggers a dialog function to display some text.")
    st.write("However, clicking the close button in the dialog causes an error.")
    st.button("Button 3 - Show Dialog - Error on Close", key="button_3",
              on_click=show_dialog, args=["button_3"])
    st.divider()


run_full_script()

Script runs locally as is
Python: 3.10
Streamlit: 1.34

Im having the same issue. Streamlit team, is there a way to fix this?

How fragments interact with callbacks is still being worked out. Officially, you can think of calling fragments as a callback as unsupported. (Dialogs are an extension of fragments.)

Generating visible elements within a callback (even if that visible element is a dialog) is a special case. Callbacks appear to “push down” the rest of the app, but if the callback is a fragment/dialog and the rest of the app doesn’t rerun, elements can get deleted and Streamlit can struggle to keep track of elements on the page. This is either because something isn’t there anymore or the indexing gets off and Streamlit looks in the wrong place.

2 Likes

Thanks for the explanation.

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