Python应用开发——30天学习Streamlit Python包进行APP的构建(14):导航和页面

发布于:2024-07-07 ⋅ 阅读:(61) ⋅ 点赞:(0)

st.navigation

配置多页面应用程序中的可用页面。

在入口点文件中使用 st.Page 定义的一个或多个页面调用 st.navigation。st.navigation 会返回当前页面,可使用 .run() 方法执行。

使用 st.navigation 时,你的入口点文件(传递给 streamlit run 的文件)就像一个路由器或框架,围绕着你的每个页面的共同元素。每次重新运行应用程序时,Streamlit 都会执行入口点文件。要执行当前页面,必须在 st.navigation 返回的页面对象上调用 .run() 方法。

为了实现动态导航,每次重新运行时都可以更新可用页面集。默认情况下,如果有多个页面,st.navigation 会在侧导航中绘制可用页面。使用 position 关键字参数可以改变这种行为。

只要程序的任何会话执行了 st.navigation 命令,程序就会忽略 pages/ 目录(跨越所有会话)。

Function signature[source]

st.navigation(pages, *, position="sidebar")

Returns

(StreamlitPage)

The current page selected by the user.

Parameters

pages (list[StreamlitPage] or dict[str, list[StreamlitPage]])

The available pages for the app.

To create labeled sections or page groupings within the navigation menu, pages must be a dictionary. Each key is the label of a section and each value is the list of StreamlitPage objects for that section.

To create a navigation menu with no sections or page groupings, pages must be a list of StreamlitPage objects.

Use st.Page to create StreamlitPage objects.

position ("sidebar" or "hidden")

The position of the navigation menu. If position is "sidebar" (default), the navigation widget appears at the top of the sidebar. If position is "hidden", the navigation widget is not displayed.

If there is only one page in pages, the navigation will be hidden for any value of position.

代码

下面的示例展示了可能的入口点文件,也就是您传递给 streamlit 运行的文件。入口点文件管理应用程序的导航,并充当页面之间的路由器。

你可以通过可调用文件或文件路径声明页面。

import streamlit as st
from page_functions import page1

pg = st.navigation([st.Page(page1), st.Page("page2.py")])
pg.run()

这段代码是使用Streamlit库创建一个简单的网页应用程序。首先,它导入了Streamlit库并从page_functions模块中导入page1函数。然后,它创建了一个名为pg的导航对象,其中包含两个页面:一个是使用page1函数创建的页面,另一个是名为"page2.py"的页面。最后,它运行了pg对象,以显示网页应用程序。

使用词典在导航菜单中创建分区。

import streamlit as st

pages = {
    "Your account" : [
        st.Page("create_account.py", title="Create your account"),
        st.Page("manage_account.py", title="Manage your account")
    ],
    "Resources" : [
        st.Page("learn.py", title="Learn about us"),
        st.Page("trial.py", title="Try it out")
    ]
}

pg = st.navigation(pages)
pg.run()

这段代码使用了Streamlit库来创建一个基于页面的导航应用。首先,定义了一个包含两个键值对的字典pages,其中键是页面的名称,值是一个包含st.Page对象的列表。每个st.Page对象代表一个页面,包括页面的文件名和标题。

然后,通过调用st.navigation(pages)创建了一个导航对象pg,该对象将使用定


网站公告

今日签到

点亮在社区的每一天
去签到