Persist display items as the user continues with st.button

Hello community,
I was thinking if there is a way to persist displayed items as the user takes next actions.
I have 3 columns with certain options. When the user clicks on a button under column 1, I would like to display the output under that column. When the user clicks on button under column 2, the display under column 1 vanishes. As per button’s documentation, I believe this is an expected behavior(Button behavior and examples - Streamlit Docs). However, I would like to know if there is a way to persist the display item, after the user goes to next actions.

Below is a screenshot of how the layout looks. As soon as I click on the Generate for column 2, the output under column 1 is gone.

Code snippet:

if "compare_count" not in st.session_state:
    st.session_state["compare_count"] = 1
if st.button("Add column"):
    st.session_state["compare_count"] += 1
ncol = st.session_state["compare_count"]

cols = st.columns(ncol)
for i, x in enumerate(cols):
    with st.form(f"form_{i}"):
        with x:
            st.select_slider("Temperature", options=[num / 10.0 for num in range(0, 11)], key=f"slide_{i}")
            st.text_input("Open AI Key", type="password", key=f"key_{i}")
            st.number_input("Max. tokens", value=256, min_value=1, step=1, key=f"token_{i}")
            prompt = st.text_area("Prompt: ", key=f"prompt_{i}")
            if st.button("Generate", key=f"button_{i}"):
                st.session_state[f"prompt_value_{i}"] = prompt
                st.write(f"Prompt for temperature {st.session_state[f'slide_{i}']} is: {st.session_state[f'prompt_value_{i}']}")

Thanks in advance. :smile:

Hi @Bharath_Muthineni

It seems that after clicking on the Submit button on one of the column, this triggers an app rerun and thus resets the session state. Have you tried refactoring the code such that the 2 columns are created individually instead of through enumerating a for loop.

Also, you could try using a callback function (define a custom function that updates the text display and use the callback via on_change or on_click from an input widget.

More details in the Docs:

Hope this helps!

Hey @dataprofessor,
I can’t really create the columns individually. There is a button which will allow the users to add and another button to remove the columns dynamically.

Also, using on_click or on_change doesn’t seem to solve the problem. I believe even these callbacks will re-run the entire applications on click. Correct me if I’m wrong.

Thank you!