使用streamlit创建一个产品指标与排名看板【2】创建一个使用sidebar+exec管理的多页面应用
1. Streamlit常见的多页面管理形式
- pages文件夹形式的多页面应用
- switch_page或者page_link跳转
- sidebar+exec形式
开始时使用的方法1,使用文件结构和文件名称管理多页面,页面内容可以不需要为导航专门再写东西,非常便捷。随着使用,缺点也很明显,无法再定义导航栏中的页面名称,运行app后是一个url/+[页面名称]的多路径形式。
后来研究怎么自定义这个页面名称,并且使用一个url访问所有页面,官方文档会推荐switch_page\page_link方法。实现时发现很容易受限于streamlit版本,最终使用了sidebar+exec的方法,路径灵活、名称可自定义而且不受限于版本。
2.多页面配置
1.文件结构
Streamlit/
config.py #配置页面
home.py #主页
common.py #页面公用方法
display1.py #页面1
display2.py #页面2
display3.py #页面3
display4.py #页面4
main.py #主程序入口
2. 页面配置编码
这里面使用了st.session.current_page全局变量记录当前的页面信息,页面导航在sidebar里定义button来实现。通过st.session.current_page的值来判断需要打开的页面exec(open("page.py"))
。
def main():
st.title("多页应用示例")
st.sidebar.title("导航菜单")
# 设置按钮宽度为容器宽度
st.sidebar.markdown(
"""
<style>
div.stButton > button {
width: 100%;
}
</style>
""",
unsafe_allow_html=True,
)
# 使用按钮实现页面跳转
if st.sidebar.button("首页"):
st.session_state.current_page = "home"
if st.sidebar.button("数据源配置"):
st.session_state.current_page = "config"
if st.sidebar.button("指标分类积分"):
st.session_state.current_page = "display1"
if st.sidebar.button("指标横向查询"):
st.session_state.current_page = "display2"
if st.sidebar.button("产品指标查询"):
st.session_state.current_page = "display3"
if st.sidebar.button("产品排名查询"):
st.session_state.current_page = "display4"
# 默认页面
if "current_page" not in st.session_state:
st.session_state.current_page = "home"
# 加载对应的页面模块
if st.session_state.current_page == "home":
exec(open("home.py").read())
elif st.session_state.current_page == "config":
exec(open("config.py").read())
elif st.session_state.current_page == "display1":
exec(open("display1.py").read())
elif st.session_state.current_page == "display2":
exec(open("display2.py").read())
elif st.session_state.current_page == "display3":
exec(open("display3.py").read())
elif st.session_state.current_page == "display4":
exec(open("display4.py").read())
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· spring官宣接入deepseek,真的太香了~