Streamlit中使用st.button切换页面报错,如何实现页面切换?
解决Streamlit按钮切换页面时
Calling st.rerun() within a callback is a no-op.报错问题 问题根源在于st.switch_page内部会调用st.rerun(),而按钮的on_click回调中不允许执行st.rerun(),因此触发报错。要保留st.button的样式定制特性同时实现页面切换,可通过会话状态标记的方式绕开回调限制:
修改后的代码
def _render_settings_button(self, column): with column.container(): # 回调仅设置页面切换标记,不直接执行切换逻辑 def mark_switch_to_settings(): st.session_state["switch_to_settings"] = True st.button( ":material/settings: Settings", key="settings_button", use_container_width=True, on_click=mark_switch_to_settings ) # 在按钮渲染完成后,主流程中检查标记并执行页面切换 if st.session_state.get("switch_to_settings", False): st.switch_page(st.session_state["pages"]["settings"]) # 重置标记,避免重复触发切换 st.session_state["switch_to_settings"] = False
逻辑说明
- 按钮回调仅负责设置会话状态标记,完全避开回调内调用
st.rerun()的限制 - 页面切换逻辑放在主代码流程中执行,确保
st.switch_page的调用符合Streamlit的运行规则 - 此方案完全保留
st.button的样式定制能力,不会影响按钮的展示效果
内容的提问来源于stack exchange,提问作者HuLu ViCa
相关产品推荐
相关产品推荐

