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 #页面1display2.py #页面2display3.py #页面3display4.py #页面4main.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())