如何在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
相关产品推荐
相关产品推荐

