1.Streamlit-Pages介绍
Streamlit原生支持多页面应用,其中页面文件名是页面设置的真实来源。但是,如果要更改侧边栏中的名称或重新排序应用中的页面,就不得不更改文件名,这有点麻烦。更糟糕的是,我真的不喜欢在文件名中放置表情符号。
这是一个实验性的包,旨在尝试如果你可以随意命名页面,并通过一个设置函数管理哪些页面可见以及它们在侧边栏中的显示方式,页面管理会如何工作。
这可以让你独立于文件名/路径来设置页面名称、图标和顺序,同时保留当前Streamlit多页面应用的侧边栏和URL行为。
2.如何使用
①方法一:在Streamlit代码内部声明页面
from st_pages import Page, show_pages, add_page_title
# Optional -- adds the title and icon to the current page
add_page_title()
# Specify what pages should be shown in the sidebar, and what their titles and icons
# should be
show_pages(
[
Page("streamlit_app.py", "Home", "🏠"),
Page("other_pages/page2.py", "Page 2", ":books:"),
]
)
如果您希望将页面组织成具有缩进关系的不同部分,并显示出哪些页面属于哪个部分,您可以按照以下步骤操作:
from st_pages import Page, Section, show_pages, add_page_title
# Either this or add_indentation() MUST be called on each page in your
# app to add indendation in the sidebar
add_page_title()
# Specify what pages should be shown in the sidebar, and what their titles and icons
# should be
show_pages(
[
Page("streamlit_app.py", "Home", "🏠"),
Page("other_pages/page2.py", "Page 2", ":books:"),
Section("My section", icon="🎈️"),
# Pages after a section will be indented
Page("Another page", icon="💪"),
# Unless you explicitly say in_section=False
Page("Not in a section", in_section=False)
]
)
②方法二:在配置文件中声明页面
.streamlit/pages.toml
文件的内容为:
(注:这里缺少具体的.streamlit/pages.toml
文件内容,请补充文件内容,以便进行准确的翻译。)
[[pages]]
path = "streamlit_app.py"
name = "Home"
icon = "🏠"
[[pages]]
path = "other_pages/page2.py"
name = "Page 2"
icon = ":books:"
举例:
[[pages]]
path = "streamlit_app.py"
name = "Home"
icon = "🏠"
[[pages]]
path = "other_pages/page2.py"
name = "Page 2"
icon = ":books:"
[[pages]]
name = "My second"
icon = "🎈️"
is_section = true
# Pages after an `is_section = true` will be indented
[[pages]]
name = "Another page"
icon = "💪"
# Unless you explicitly say in_section = false`
[[pages]]
name = "Not in a section"
in_section = false
Streamlit code:
from st_pages import show_pages_from_config, add_page_title
# Either this or add_indentation() MUST be called on each page in your
# app to add indendation in the sidebar
add_page_title()
show_pages_from_config()
③隐藏页面
现在,您可以传递一个页面名称列表给hide_pages
函数,以便为每个用户动态隐藏页面。请注意,这些页面仅通过CSS隐藏,仍然可以通过URL进行访问。但是,如果您只是想通过视觉方式引导用户接下来应该去哪里,这可能是一个不错的选择。
注意:您应该只隐藏那些已经添加到侧边栏的页面。
show_pages(
[
Page("streamlit_app.py", "Home", "🏠"),
Page("another.py", "Another page"),
]
)
hide_pages(["Another page"])