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

如何在Tkinter窗口中呈现类似table()或终端效果的pandas DataFrame?

两种在Tkinter中显示Pandas DataFrame的方案

你想要的两种效果分别对应下面两个轻量实现方案,不需要复杂的pandastable,也能避开Treeview的简陋样式:

方案一:和终端显示完全一致的样式

直接用Tkinter的Text组件展示DataFrame的字符串格式,搭配滚动条适配长数据:

from tkinter import *
from tkinter import ttk
import pandas as pd
import numpy as np

root = Tk()
root.title("终端风格DataFrame")

# 构建带滚动条的文本容器
container = Frame(root)
scrollbar = ttk.Scrollbar(container)
text_box = Text(container, wrap=NONE, yscrollcommand=scrollbar.set)
scrollbar.config(command=text_box.yview)

scrollbar.pack(side=RIGHT, fill=Y)
text_box.pack(fill=BOTH, expand=YES)
container.pack(fill=BOTH, expand=YES, padx=5, pady=5)

# 生成DataFrame并插入到文本框
df = pd.DataFrame(np.random.randint(0,100,size=(10, 4)), columns=list('ABCD'))
text_box.insert(END, df.to_string())

root.mainloop()

这个方案完全复用了pandas自带的终端输出格式,实现简单,不需要额外依赖,适合追求简洁一致的场景。

方案二:和IPython table()函数一致的HTML表格样式

用轻量库tkhtmlview来渲染HTML,效果和你调用display(HTML(df.to_html()))完全一致:

  1. 先安装依赖:
pip install tkhtmlview
  1. 实现代码:
from tkinter import *
import pandas as pd
import numpy as np
from tkhtmlview import HTMLLabel

root = Tk()
root.title("HTML风格DataFrame")

# 生成DataFrame并转换为HTML(可自定义CSS美化)
df = pd.DataFrame(np.random.randint(0,100,size=(10, 4)), columns=list('ABCD'))
html_content = f"""
<style>
table {{border-collapse: collapse; width: 100%;}}
th, td {{border: 1px solid #ddd; padding: 8px; text-align: center;}}
th {{background-color: #f2f2f2;}}
</style>
{df.to_html(index=False)}
"""

# 用HTMLLabel渲染HTML内容
html_label = HTMLLabel(root, html=html_content, background='white')
html_label.pack(fill=BOTH, expand=YES, padx=10, pady=10)

root.mainloop()

这个方案支持自定义表格样式,比Treeview美观很多,同时比pandastable轻便,完全满足你的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 17:53:11