Nested buttons

Summary

I am building text summarizer with user feedback for validating a LLM model. However, the code below the line if st.button(“Submit”) doesn’t seem to work. Please advise how to fix the second button.

Steps to reproduce

Code snippet:

import streamlit as st

def main():
    summary = None
    st.title("Text Summarization")

    # User input
    input_text = st.text_area("Enter the text you want to summarize:", height=200)

    # Summarize button
    if st.button("Summarize"):
        if input_text:
            summary = 'This is a summary of the input text.'
            # Display the summary as bullet points
            st.subheader("Summary:")
            st.write(summary)
        else:
            st.warning("Please enter text to summarize.")

    if summary:
        input_feedback = st.text_area("Submit feedback:", height=100)
        st.write('All good until here')
        if st.button("Submit"):
          st.write("User feedback and summary is now saved.")

if __name__ == "__main__":
    main()

If applicable, please provide the steps we should take to reproduce the error or specified behavior.

Expected behavior:

I would like to see the text “User feedback and summary is now saved.” written after clicking the submit button.

Actual behavior:

Nothing happens after I click the Submit button

Hello @aaq109 and welcome to the community!

When using and if button approach, the second button event will override the first. Instead, you would want to use Session State and Callbacks to make your app stateful. I modified your code a bit to demonstrate.

import streamlit as st


if "summary" not in st.session_state:
    st.session_state["summary"] = None


def set_summary(summary: str):
    st.session_state["summary"] = summary


def main():
    summary = None
    st.title("Text Summarization")

    # User input
    input_text = st.text_area("Enter the text you want to summarize:", height=200)

    # Summarize button
    if input_text:  # SHOWS THE BUTTON IF TEXTBOX IS NOT EMPTY
        st.button("Summarize", on_click=set_summary, args=[input_text])
        if st.session_state["summary"] != None:
            summary = "This is a summary of the input text."
            # Display the summary as bullet points
            st.subheader("Summary:")
            st.write(summary)
    else:
        st.warning("Please enter text to summarize.")

    if summary:
        input_feedback = st.text_area("Submit feedback:", height=100)
        st.write("All good until here")
        if st.button("Submit"):
            st.write("User feedback and summary is now saved.")


if __name__ == "__main__":
    main()

Also, you can read more about stateful apps here → Here

Cheers,

Carlos

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