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

Tkinter展示yfinance数据时日期索引显示异常问题

Tkinter Treeview无法显示yfinance日期索引的解决办法

问题根源

  1. 插入表格时把日期用{}包成了集合,Treeview无法识别这种类型,导致显示异常
  2. yfinance返回的日期是Timestamp对象,直接传入Treeview会显示晦涩的格式
  3. Treeview初始化代码里存在拼写错误:tex=col应该是text=col,会导致表头显示异常

修复步骤

1. 修正日期格式与插入逻辑

替换原插入表格的代码为:

# 倒序遍历数据行并插入Treeview
for date, row in reversed(list(self.data.iterrows())):
    self.data_table.insert("", tk.END, values=(
        date.strftime("%Y-%m-%d %H:%M:%S"),  # 将时间戳转换为可读字符串格式
        f'${row["Open"]:.2f}',
        f'${row["Close"]:.2f}',
        f'${row["Low"]:.2f}',
        f'${row["High"]:.2f}',
        f'${row["Adj Close"]:.2f}',
        f'{row["Volume"]:.0f}'  # 成交量用整数显示更符合阅读习惯
    ))
  • 使用iterrows()直接获取日期索引和行数据,比通过下标遍历更简洁直观
  • 用strftime()自定义日期格式:仅需日期可改为%Y-%m-%d,需带时间则保留%Y-%m-%d %H:%M:%S
  • 删除包裹日期的{},避免向Treeview传入集合类型数据

2. 修复Treeview表头拼写错误

找到Treeview初始化代码中的对应片段,将tex=col修正为text=col:

for col in ("Open","High", "Low","Close", "Adj Close", "Volume"):
    self.data_table.heading(col, text=col, anchor=tk.CENTER)  # 修正tex为text
    self.data_table.column(col, anchor=tk.E)

可选优化:将索引转为普通列

如果后续需要对日期做更多操作,可以在获取数据时将索引转为独立列:

def obtener_datos_criptomoneda(self, activo, periodo, temporalidad):
    data_yfinance = yf.download(activo, interval=temporalidad, period=periodo)
    self.data = data_yfinance.dropna().reset_index()  # 重置索引,日期转为"Date"列
    # 后续保存CSV或插入表格时,直接调用self.data["Date"]即可

修正后的完整核心代码

插入表格代码

# 倒序插入数据到Treeview
for date, row in reversed(list(self.data.iterrows())):
    self.data_table.insert("", tk.END, values=(
        date.strftime("%Y-%m-%d %H:%M"),
        f'${row["Open"]:.2f}',
        f'${row["Close"]:.2f}',
        f'${row["Low"]:.2f}',
        f'${row["High"]:.2f}',
        f'${row["Adj Close"]:.2f}',
        f'{row["Volume"]:.0f}'
    ))

Treeview初始化代码

scroll_x = tk.Scrollbar(self.center_frame, orient="horizontal")
scroll_x.pack(side=tk.BOTTOM, fill=tk.X)
scroll_y = tk.Scrollbar(self.center_frame, orient="vertical")
scroll_y.pack(side=tk.RIGHT, fill=tk.Y)

self.data_table = ttk.Treeview(
    self.center_frame,
    columns=["Date", "Open","High", "Low","Close", "Adj Close", "Volume"],
    show="headings"
)

# 设置表头和列属性
for col in ["Date", "Open","High", "Low","Close", "Adj Close", "Volume"]:
    self.data_table.heading(col, text=col, anchor=tk.CENTER)
    if col == "Date":
        self.data_table.column(col, anchor=tk.CENTER, width=150)  # 日期列加宽避免显示不全
    else:
        self.data_table.column(col, anchor=tk.E, width=100)  # 数值列右对齐,符合阅读习惯

# 绑定滚动条
scroll_x.config(command=self.data_table.xview)
scroll_y.config(command=self.data_table.yview)
self.data_table.config(xscrollcommand=scroll_x.set, yscrollcommand=scroll_y.set)
self.data_table.pack(pady=20, padx=20, fill=tk.BOTH, expand=True)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 01:51:03