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:
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:
Folder Setup: The pages/ directory contains the additional pages (page1.py, page2.py). This is how Streamlit manages multiple pages.
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").
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.
@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)