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

Streamlit中st.spinner多数情况下无法显示的技术问题

Streamlit中st.spinner不显示的问题解决

问题原因

  1. 触发逻辑不合理:你使用if query:作为触发条件,用户输入任何内容后(无需点击提交按钮)页面就会重跑并执行查询,导致spinner还没完成渲染就可能已经执行完逻辑,无法显示。
  2. 执行速度过快:如果custom_qa.qa.run(query)执行耗时极短,Streamlit来不及渲染spinner组件,只会显示右上角默认的"Running"提示。

解决方案

1. 绑定提交按钮作为触发条件

将触发逻辑改为仅在用户点击提交按钮且查询内容非空时执行,避免不必要的页面重跑,确保spinner有足够时间渲染:

with st.container():
    query = st.text_area("**Ask a question here:**", height=100, key="query_text")
    button = st.button("Submit", key="button")
# 仅当按钮点击且查询内容不为空时执行查询
if button and query:
    with st.spinner('Fetching Answer...'):
        response = custom_qa.qa.run(query)
        st.info(response.strip())

2. 给渲染留缓冲时间(可选)

如果查询逻辑执行速度极快,可在spinner块内添加短暂延迟,确保组件能渲染出来:

if button and query:
    with st.spinner('Fetching Answer...'):
        import time
        time.sleep(0.1)  # 给渲染留0.1秒缓冲
        response = custom_qa.qa.run(query)
        st.info(response.strip())

3. 优化文档初始化逻辑

如果call_custom_qna是耗时操作,给它也加上spinner,避免阻塞页面渲染影响后续组件:

if st.session_state.qa is None:
    with st.spinner('Processing document...'):
        with tempfile.NamedTemporaryFile(delete=False) as temp_file:
            temp_file.write(uploaded_file.getvalue())
            temp_file_path = temp_file.name
        st.session_state.qa = call_custom_qna(temp_file_path, model)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 13:30:09