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

解决Streamlit发送消息时聊天界面自动滚动异常问题

Streamlit v1.29.0聊天机器人页面跳转问题解决方案
  • 锁定聊天容器滚动位置
    自定义CSS固定聊天区域的滚动行为,避免重渲染时触发异常跳转:

    st.markdown("""
    <style>
    .stChatMessageContainer {
        overflow-y: auto;
        height: 70vh;
        scroll-behavior: smooth;
    }
    </style>
    """, unsafe_allow_html=True)
    
    chat_container = st.container()
    with chat_container:
        for msg in st.session_state.messages:
            st.chat_message(msg["role"]).write(msg["content"])
    

    也可以在消息发送后用JavaScript强制滚动到底部:

    st.components.v1.html("""
    <script>
    const chatContainer = document.querySelector('.stChatMessageContainer');
    chatContainer.scrollTop = chatContainer.scrollHeight;
    </script>
    """, height=0)
    
  • 固定输入框位置
    通过CSS将输入框固定在页面底部,防止重渲染时输入框位置变化引发页面滚动:

    st.markdown("""
    <style>
    .stTextInput {
        position: fixed;
        bottom: 20px;
        left: 50%;
        transform: translateX(-50%);
        width: 80%;
    }
    </style>
    """, unsafe_allow_html=True)
    
    user_input = st.text_input("输入消息:", key="user_input")
    
  • 优化Session State更新逻辑
    确保消息仅在输入提交后一次性添加到Session State,避免不必要的组件重渲染:

    if user_input:
        st.session_state.messages.append({"role": "user", "content": user_input})
        st.session_state.messages.append({"role": "assistant", "content": "AI回复内容"})
        st.rerun()
    
  • 调整Streamlit版本
    该问题可能是v1.29.0的特定bug,尝试降级到v1.28.2或升级至最新稳定版:

    # 降级版本
    pip install streamlit==1.28.2
    # 升级至最新版
    pip install --upgrade streamlit
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 15:07:13