How to keep the output of a button on MultiPage Setting?

I have a multipage app with two subpages. A button outputs a graphic when the button is clicked. If I now change the page via navigation and back again, the output of the button is gone. But how can I keep the old output there? It should only update the output (graphic) when I click again on the button.

I tried submit_form elements but still the output of the button is gone, if switch between the subpages. Is there a solution?

You might be looking for st.session_state.

Based on your description, the general structure should work.

# importing libraries
import streamlit as st
import matplotlib.pyplot as plt

# define generic ploting function
def plot():
    fig, ax = plt.subplots()
    ax = plt.plot([1, 2, 3, 4])
    plt.ylabel('some numbers')
    return fig


# create sidebar-selectbox for multi-pages
page = st.sidebar.selectbox(label='page', options=('Page One', 'Page Two'))

# define first page of app
if page == 'Page One':
    st.title(body='Plotting Page')
    if st.button(label='Plot'):
        # create the plot then display it
        fig = plot()
        st.pyplot(fig)
        
        # save the plot to session state
        st.session_state.plot = fig

# define second page of app  
else:
    st.title(body='Second Page')
    if st.button(label='recall plot'):
        
        # recall plot from session state
        fig = st.session_state.plot
        st.pyplot(fig)

Your example shows the problem very well. If I click the button on page 1 and then switch to page 2 and back to page 1 the output is gone. (I have to click button on page 1 again…). I tried also with session states but it does not hold the output on multipages.

Okay, I think I understand your problem better now. What you want to do is then, check if the plot exists in the session state, if true you plot it, else you must click the button to create the plot for the first time.

# importing libraries
import streamlit as st
import matplotlib.pyplot as plt

# define generic ploting function
def plot():
    fig, ax = plt.subplots()
    ax = plt.plot([1, 2, 3, 4])
    plt.ylabel('some numbers')
    return fig


# create sidebar-selectbox for multi-pages
page = st.sidebar.selectbox(label='page', options=('Page One', 'Page Two'))

# define first page of app
if page == 'Page One':
    st.title(body='Plotting Page')
    
    # check if plot is already in session state
    if 'plot' in st.session_state:
        fig = st.session_state.plot
        st.pyplot(fig)
    elif st.button(label='Plot'):
        # create the plot then display it
        fig = plot()
        st.pyplot(fig)
        
        # save the plot to session state
        st.session_state.plot = fig

# define secon page of app  
else:
    st.title(body='Second Page')
    if st.button(label='recall plot'):
        
        # recall plot from session state
        fig = st.session_state.plot
        st.pyplot(fig)