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

如何在Streamlit中点击Logout按钮后隐藏侧边栏?

解决Streamlit点击Logout后完全隐藏侧边栏的问题

原代码的问题在于:只隐藏了侧边栏的折叠控件,没处理侧边栏本身;而且authenticator.logout()的返回值逻辑没法稳定触发样式更新。试试下面的修改方案:

import streamlit as st
from streamlit_authenticator import Authenticator

# 这里需要你自行初始化authenticator(配置credentials、cookie参数等)
# authenticator = Authenticator(credentials, "auth_cookie", "auth_key", 30)

name, authentication_status, username = authenticator.login("Login", "main")

# 监听logout的session状态
if st.session_state.get('logout'):
    # 用CSS彻底隐藏侧边栏及触发按钮
    st.markdown("""
    <style>
        /* 直接隐藏侧边栏容器 */
        [data-testid="stSidebar"] {
            display: none !important;
        }
        /* 隐藏顶部的侧边栏折叠按钮 */
        [data-testid="collapsedControl"] {
            display: none !important;
        }
    </style>
    """, unsafe_allow_html=True)
    # 重置logout状态,避免页面刷新后样式一直生效
    st.session_state['logout'] = False

# 放置Logout按钮到侧边栏
authenticator.logout("Logout", "sidebar")

核心修改点:

  • 改用st.session_state['logout']来判断是否点击了Logout按钮,这个状态是authenticator.logout()内置设置的,比直接判断返回值更可靠
  • CSS同时隐藏侧边栏容器和折叠按钮,添加!important强制覆盖Streamlit的默认样式
  • 处理完样式后重置logout状态,防止后续页面交互受影响

内容的提问来源于stack exchange,提问作者Abdul Awal Nadim

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 19:37:09