You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Streamlit中自定义侧边栏(页面)以划分多个板块?

Streamlit自定义侧边栏实现页面分组展示

核心思路

Streamlit默认多页面侧边栏不支持原生分组,需要禁用默认页面导航,手动通过st.sidebar组件构建分组导航,再用st.switch_page()实现页面跳转。

实现步骤

1. 调整项目结构

保持原有页面结构,后续按需添加Drops板块页面:

/Home.py
/pages/Add_Pickups.py
/pages/View_Pickups.py
/pages/Add_Drops.py
/pages/View_Drops.py

2. 禁用默认页面导航

在所有页面的最开头添加代码,隐藏默认的多页面导航栏:

import streamlit as st

# 隐藏侧边栏默认导航(适配Streamlit 1.28+版本)
st.markdown(
    """
    <style>
        [data-testid="stSidebarNav"] {display: none;}
    </style>
    """,
    unsafe_allow_html=True
)

3. 手动构建分组侧边栏导航

为了统一所有页面的侧边栏样式,建议把导航逻辑封装成工具函数,新建utils.py模块:

import streamlit as st

def build_grouped_sidebar():
    with st.sidebar:
        # Pickups板块
        st.subheader("Pickups")
        if st.button("Add Pickups"):
            st.switch_page("pages/Add_Pickups.py")
        if st.button("View Pickups"):
            st.switch_page("pages/View_Pickups.py")
        
        # 板块分隔线
        st.divider()
        
        # Drops板块
        st.subheader("Drops")
        if st.button("Add Drops"):
            st.switch_page("pages/Add_Drops.py")
        if st.button("View Drops"):
            st.switch_page("pages/View_Drops.py")

4. 在各页面中调用导航函数

每个页面开头导入并调用工具函数,比如Add_Pickups.py:

import streamlit as st
from utils import build_grouped_sidebar

# 渲染自定义分组侧边栏
build_grouped_sidebar()

# 页面原有业务逻辑
st.title("Add Pickups")
# ... 后续CRUD代码

注意事项

  • st.switch_page()要求Streamlit版本≥1.18.0,请确保环境符合要求。
  • 若需要更美观的样式,可自定义CSS调整按钮外观,或用st.radio、st.selectbox替代按钮实现导航。
  • 新增板块时,只需在build_grouped_sidebar()函数中添加对应分组和跳转逻辑即可。

内容的提问来源于stack exchange,提问作者Minura Punchihewa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 21:31:01