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

Streamlit中st.button搭配st.chat_input点击后页面空白问题咨询

解决Streamlit按钮点击后页面重置、内容丢失的问题

问题原因

Streamlit的运行机制是每次用户交互(如点击按钮、输入内容)都会重新执行整个脚本。原代码中:

  • 用户输入仅存于临时变量user_question,按钮触发重跑后该变量会被重置为空,导致之前展示的输入内容消失;
  • 按钮的点击状态仅在单次脚本运行中有效,反馈提示无法在重跑后保留。

解决方案

通过st.session_state持久化用户输入和反馈状态,确保重跑脚本时数据不丢失。修改后的代码如下:

import streamlit as st

# 初始化session_state变量,避免首次运行报错
if "user_question" not in st.session_state:
    st.session_state.user_question = ""
if "feedback_msg" not in st.session_state:
    st.session_state.feedback_msg = ""

st.write("Please provide feedback for the above content as correct, incorrect, or incomplete.")

# 处理用户输入,存入session_state
user_input = st.chat_input("Enter the question here:")
if user_input:
    st.session_state.user_question = user_input
    # 输入新内容时清空之前的反馈提示
    st.session_state.feedback_msg = ""

# 展示用户输入内容(如果存在)
if st.session_state.user_question:
    st.write("Your question is:", st.session_state.user_question)

    # 添加反馈按钮,点击时更新session_state中的反馈提示
    col1, col2 = st.columns(2)
    with col1:
        if st.button("👍 Thumbs Up"):
            st.session_state.feedback_msg = "Thanks for providing the feedback!"
    with col2:
        if st.button("👎 Thumbs Down"):
            st.session_state.feedback_msg = "Thanks for providing the feedback. We will improve the content."

# 展示反馈提示(如果存在)
if st.session_state.feedback_msg:
    st.write(st.session_state.feedback_msg)

关键修改说明

  • 初始化session_state:首次运行脚本时创建user_question和feedback_msg变量,避免后续访问报错;
  • 持久化用户输入:将chat_input获取的内容存入st.session_state.user_question,重跑时仍能读取到之前的输入;
  • 更新反馈状态:点击按钮时,将对应反馈文本存入st.session_state.feedback_msg,而非直接在按钮分支中写内容;
  • 独立渲染反馈:在按钮分支外根据session_state的值渲染反馈提示,确保重跑后仍能显示。

内容的提问来源于stack exchange,提问作者Ram Balakrishna

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 11:37:15