python-3.xpandasweb-applicationssocial-networkingstreamlit

streamlit web app that has multiple page and the "back home" button


I have a streamlit web app that has four navigation radio buttons. What I want for app is to show all the navigation buttons when only the home button is selected. If other buttons are selected then the sidebar should only show one button with the text 'back home'. Here below is the code I used:

import streamlit as st


## Home Page  
    
rad = st.sidebar.radio("Navigation", ['Home','Summary', 'Twitter','Facebook'])


if rad == 'Home':   
   st.title('Sidebar should show all navigation buttons from the list above')

if rad == 'Summary':
    st.title('Sidebar should only show backhome button')

if rad == 'Twitter':
    st.title('Sidebar should only show backhome button')

if rad == 'Facebook':
    st.title('Sidebar should only show backhome button')

   

Solution

  • With a simulated multipage structure like you have, you'll need to create a value in session state to save what page you are on. Then, dependent on that value you can display the appropriate navigation. Use callback functions from those navigation widgets to modify the saved page in session state.

    import streamlit as st
    
    if 'page' not in st.session_state:
        st.session_state.page = 'Home'
    
    def set_page():
        st.session_state.page = st.session_state.nav
    
    def home():
        st.session_state.page = 'Home'
    
    if st.session_state.page == 'Home':
        st.sidebar.radio(
            "Navigation",
            ['Home','Summary', 'Twitter','Facebook'], 
            key='nav',
            on_change=set_page
        )
    else:
        st.sidebar.button('Back to Home', on_click=home)
    
    match st.session_state.page:
        case 'Home':
            st.title('Home')
        case 'Summary':
            st.title('Summary')
        case 'Twitter':
            st.title('Twitter')
        case 'Facebook':
            st.title('Facebook')