Using st.pages & st.navigation to create selectbox selector

trying to create more personal navigation for when selecting st.pages, below is simplified example. But in doing this below it just ends up in infinite loop:

from __future__ import annotations

import streamlit as st

def page1():
    st.title("Hello")


def page2():
    st.title("Bye")

pg1 = st.Page(page1)
pg2 = st.Page(page2)

pages = [pg1, pg2]

pg = st.navigation(
    pages=pages,
    position="hidden",
)
pg.run()

page = st.sidebar.selectbox("Select Page", pages, format_func=lambda x: x.title)
st.switch_page(page)

Hey @ksdaftari ,

You can use Streamlit’s built-in page navigation system with st.switch_page() to create a personal navigation experience without running into infinite loops. Here’s how you can set it up:

Step 1: Folder Structure

First, make sure your folder structure follows the new Streamlit convention for multiple pages. It should look something like this:

your_app/
│
├── app.py  # The main file
└── pages/
    ├── page1.py
    └── page2.py

Step 2: In app.py (Main Page)

import streamlit as st

st.title("Main Page")

# Sidebar to select a page
page = st.sidebar.selectbox("Select Page", ["Main", "Page 1", "Page 2"])

# Use st.switch_page to navigate to the selected page
if page == "Page 1":
    st.switch_page("page1")
elif page == "Page 2":
    st.switch_page("page2")

Step 3: In pages/page1.py

import streamlit as st

st.title("Page 1")

# Provide navigation back to the main page or other pages
st.sidebar.button("Go to Main", on_click=lambda: st.switch_page("app"))
st.sidebar.button("Go to Page 2", on_click=lambda: st.switch_page("page2"))

Step 4: In pages/page2.py

import streamlit as st

st.title("Page 2")

# Provide navigation back to the main page or other pages
st.sidebar.button("Go to Main", on_click=lambda: st.switch_page("app"))
st.sidebar.button("Go to Page 1", on_click=lambda: st.switch_page("page1"))

Explanation:

  1. Folder Setup: The pages/ directory contains the additional pages (page1.py, page2.py). This is how Streamlit manages multiple pages.
  2. st.switch_page(): You use st.switch_page() to navigate between pages by specifying the name of the file (without the .py extension). For example, to switch to page1.py, you use st.switch_page("page1").
  3. Custom Sidebar Navigation: The sidebar lets the user select between pages, and when a page is selected, it uses st.switch_page() to navigate. No infinite loops, and navigation is smooth and controlled.

Let me know if you need further clarification!

Cheers,
Nico

@Nico is there way to do with specifying st.Page(…) and not require the specific pages/ directory. there are some specific items trying to accomplish, but part is to allow more auto discovery features and not rely on the specific flat folder structure of pages/ (among some other items that makes using st.Page to specify file and list of pages better)