In Streamlit, navigation between pages is a powerful feature for building dynamic multi-page applications. This tutorial will explore page navigation in Streamlit, using the new st.navigation
, st.page_link
and st.switch_page
methods to create a seamless user experience.
Why choose multi-page application?
Streamlit was not originally built as a multi-page application framework. However, as it evolved, the Streamlit team introduced features to support multi-page applications. These features simplify navigation and provide customizable options for dynamic web applications.
Project structure settings
In this tutorial, our project structure follows the following layout:
<code>project/ │ ├── app.py # 主應(yīng)用程序文件 ├── app_pages/ │ ├── intro.py │ ├── navigation_intro.py │ ├── page_link_demo.py │ ├── switch_page_demo.py </code>
app_pages
Each file in the directory represents an individual page in the application.
Implement navigation: app.py
Let’s start by defining the page in app.py
. This file uses st.navigation
to set up the navigation menu.
# app.py import streamlit as st # 頁(yè)面導(dǎo)航 pages = [ st.Page("app_pages/intro.py", title="簡(jiǎn)介", icon="?"), st.Page("app_pages/navigation_intro.py", title="st.navigation", icon="?"), st.Page("app_pages/page_link_demo.py", title="st.page_link", icon="?"), st.Page("app_pages/switch_page_demo.py", title="st.switch_page", icon="?"), ] # 將頁(yè)面添加到側(cè)邊欄導(dǎo)航 pg = st.navigation(pages, position="sidebar", expanded=True) # 運(yùn)行應(yīng)用程序 pg.run()
With this setting, the sidebar navigation will be automatically generated to display the specified page and its icon.
Page 1: Introduction
intro.py
file is used as the home page.
# app_pages/intro.py import streamlit as st def intro(): st.title("Streamlit 頁(yè)面導(dǎo)航教程") st.write("歡迎來(lái)到本Streamlit頁(yè)面導(dǎo)航教程!") st.write("使用側(cè)邊欄在不同頁(yè)面之間導(dǎo)航。") if __name__ == "__page__": intro()
When users visit this page, they will see an introduction to the application and instructions on how to navigate.
Page 2: Learn about st.navigation
Thenavigation_intro.py
document explains how to use st.navigation
.
# app_pages/navigation_intro.py import streamlit as st def navigation_intro(): st.title("st.navigation簡(jiǎn)介") st.write("`st.navigation`函數(shù)配置多頁(yè)面Streamlit應(yīng)用程序。") st.code(""" pages = [ st.Page("app_pages/intro.py", title="簡(jiǎn)介", icon="?"), st.Page("app_pages/page1.py", title="頁(yè)面1", icon="1??"), st.Page("app_pages/page2.py", title="頁(yè)面2", icon="2??"), ] pg = st.navigation(pages) pg.run() """, language="python") st.write("這將創(chuàng)建一個(gè)側(cè)邊欄菜單,其中包含`pages`列表中指定的頁(yè)面。") if __name__ == "__page__": navigation_intro()
Page 3: Use st.page_link
The page_link_demo.py
file demonstrates links between internal and external pages.
# app_pages/page_link_demo.py import streamlit as st def page_link(): st.title("使用st.page_link") st.page_link("app_pages/intro.py", label="跳轉(zhuǎn)到簡(jiǎn)介", icon="?") st.page_link("app_pages/page_link_demo.py", label="刷新本頁(yè)", icon="?") st.page_link("https://www.streamlit.io/", label="訪問(wèn)Streamlit", icon="?") if __name__ == "__page__": page_link()
This method allows users to navigate within the application or jump to external resources.
Page 4: Programmatic navigation using st.switch_page
switch_page_demo.py
Document demonstrating switching pages programmatically.
# app_pages/switch_page_demo.py import streamlit as st def switch_page(): st.title("使用st.switch_page") st.write("`st.switch_page`允許您以編程方式切換頁(yè)面。") st.code(""" if st.button("跳轉(zhuǎn)到簡(jiǎn)介"): st.switch_page("app_pages/intro.py") """, language="python") if st.button("跳轉(zhuǎn)到簡(jiǎn)介"): st.switch_page("app_pages/intro.py") if __name__ == "__page__": switch_page()
This method decouples navigation from the sidebar, providing more control over when and how users switch pages.
Conclusion
Streamlit’s navigation features make it easy to build user-friendly multi-page applications. Using st.navigation
, st.page_link
, and st.switch_page
, you can create an intuitive and dynamic navigation experience.
? Get the code: GitHub - jamesbmour/blog_tutorials
?Related Streamlit tutorial: JustCodeIt
?Support my work: Buy Me a Coffee
The above is the detailed content of Streamlit Part Page Navigation Simplified. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Polymorphism is a core concept in Python object-oriented programming, referring to "one interface, multiple implementations", allowing for unified processing of different types of objects. 1. Polymorphism is implemented through method rewriting. Subclasses can redefine parent class methods. For example, the spoke() method of Animal class has different implementations in Dog and Cat subclasses. 2. The practical uses of polymorphism include simplifying the code structure and enhancing scalability, such as calling the draw() method uniformly in the graphical drawing program, or handling the common behavior of different characters in game development. 3. Python implementation polymorphism needs to satisfy: the parent class defines a method, and the child class overrides the method, but does not require inheritance of the same parent class. As long as the object implements the same method, this is called the "duck type". 4. Things to note include the maintenance

Iterators are objects that implement __iter__() and __next__() methods. The generator is a simplified version of iterators, which automatically implement these methods through the yield keyword. 1. The iterator returns an element every time he calls next() and throws a StopIteration exception when there are no more elements. 2. The generator uses function definition to generate data on demand, saving memory and supporting infinite sequences. 3. Use iterators when processing existing sets, use a generator when dynamically generating big data or lazy evaluation, such as loading line by line when reading large files. Note: Iterable objects such as lists are not iterators. They need to be recreated after the iterator reaches its end, and the generator can only traverse it once.

The key to dealing with API authentication is to understand and use the authentication method correctly. 1. APIKey is the simplest authentication method, usually placed in the request header or URL parameters; 2. BasicAuth uses username and password for Base64 encoding transmission, which is suitable for internal systems; 3. OAuth2 needs to obtain the token first through client_id and client_secret, and then bring the BearerToken in the request header; 4. In order to deal with the token expiration, the token management class can be encapsulated and automatically refreshed the token; in short, selecting the appropriate method according to the document and safely storing the key information is the key.

A common method to traverse two lists simultaneously in Python is to use the zip() function, which will pair multiple lists in order and be the shortest; if the list length is inconsistent, you can use itertools.zip_longest() to be the longest and fill in the missing values; combined with enumerate(), you can get the index at the same time. 1.zip() is concise and practical, suitable for paired data iteration; 2.zip_longest() can fill in the default value when dealing with inconsistent lengths; 3.enumerate(zip()) can obtain indexes during traversal, meeting the needs of a variety of complex scenarios.

TypehintsinPythonsolvetheproblemofambiguityandpotentialbugsindynamicallytypedcodebyallowingdeveloperstospecifyexpectedtypes.Theyenhancereadability,enableearlybugdetection,andimprovetoolingsupport.Typehintsareaddedusingacolon(:)forvariablesandparamete

InPython,iteratorsareobjectsthatallowloopingthroughcollectionsbyimplementing__iter__()and__next__().1)Iteratorsworkviatheiteratorprotocol,using__iter__()toreturntheiteratorand__next__()toretrievethenextitemuntilStopIterationisraised.2)Aniterable(like

Assert is an assertion tool used in Python for debugging, and throws an AssertionError when the condition is not met. Its syntax is assert condition plus optional error information, which is suitable for internal logic verification such as parameter checking, status confirmation, etc., but cannot be used for security or user input checking, and should be used in conjunction with clear prompt information. It is only available for auxiliary debugging in the development stage rather than substituting exception handling.

To test the API, you need to use Python's Requests library. The steps are to install the library, send requests, verify responses, set timeouts and retry. First, install the library through pipinstallrequests; then use requests.get() or requests.post() and other methods to send GET or POST requests; then check response.status_code and response.json() to ensure that the return result is in compliance with expectations; finally, add timeout parameters to set the timeout time, and combine the retrying library to achieve automatic retry to enhance stability.
