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

Streamlit多列展示实时股票数据:解决值追加而非覆盖问题

解决Streamlit实时价格不覆盖、持续追加的问题

问题核心是你在while True循环内部重复创建st.empty()容器,导致每次循环都在列中新增内容而非覆盖原有内容。同时直接用while True会阻塞Streamlit的渲染流程,改用框架自带的自动刷新机制更合理。

修改后的代码

import streamlit as st
import yfinance as yf

st.set_page_config(page_title="Test", layout='wide')
tech_list = ['btc-usd', 'eth-usd']
etf_list = ['etc-usd']

# 初始化列布局
(tech_ticker, tech_price, etf_ticker, etf_price, crypto_ticker, crypto_price,
finance_ticker, finance_price, transport_ticker, transport_price) = st.columns(10, gap='small')

# 固定显示股票代码
with tech_ticker:
    for val in tech_list:
        st.write(val)

with etf_ticker:
    for val in etf_list:
        st.write(val)

# 为每个股票价格提前创建对应的空容器(放在刷新逻辑外部)
tech_price_boxes = [st.empty() for _ in tech_list]
etf_price_boxes = [st.empty() for _ in etf_list]

# 设置自动刷新间隔(单位:毫秒,这里设为5秒刷新一次)
st.autorefresh(interval=5000, key="price_refresh")

# 实时更新价格
with tech_price:
    for idx, ticker in enumerate(tech_list):
        stock = yf.Ticker(ticker)
        price = stock.info['regularMarketPrice']
        tech_price_boxes[idx].write(f": {round(price, 1)}")

with etf_price:
    for idx, ticker in enumerate(etf_list):
        stock = yf.Ticker(ticker)
        price = stock.info['regularMarketPrice']
        etf_price_boxes[idx].write(f": {round(price, 1)}")

关键调整说明

  • 替换阻塞循环为自动刷新:Streamlit原生支持st.autorefresh触发页面刷新,避免while True导致的线程阻塞问题。
  • 提前初始化空容器:把每个股票对应的价格容器放在刷新逻辑外,每次刷新时直接更新容器内的内容,而非重复创建新容器追加内容。
  • 容器与股票一一绑定:用列表存储每个股票的价格容器,确保价格更新到对应股票的位置,避免错位。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 11:25:18