Skip to main content
 首页 » 编程设计

python之在 Tkinter 的表格中显示数据的最佳方式是什么

2025年05月04日23tintown

我编写了一个从文本文件中获取数据并以表格样式格式显示的程序。

来自文本文件的数据:

Jim,0.33 
Dave,0.67 
James,0.67 
Eden,0.5 

使用程序格式化:

Position | Name              |Score 
----------------------------------- 
1        |Dave               |0.67 
2        |James              |0.67 
3        |Eden               |0.5 
4        |Jim                |0.33 

在不导入 Pandas/SQL 等的情况下,是否有更好的方式来显示这些数据?

我写的代码如下:

from tkinter import * 
 
def show(): 
 
    tempList= [['Jim', '0.33'], ['Dave', '0.67'], ['James', '0.67'], ['Eden', '0.5']] 
 
    tempList.sort(key=lambda e: e[1], reverse=True) 
    listBox.insert(END, "Position | Name      \t\t |Score\n") 
    listBox.insert(END,"-----------------------------------") 
    listBox.insert(END,"\n") 
 
    for i in range(len(tempList)): 
        listBox.insert(END,(i+1)) 
        listBox.insert(END,"\t |") 
        listBox.insert(END,tempList[i][0]) 
        listBox.insert(END,"\t \t|") 
        listBox.insert(END,tempList[i][1]) 
        listBox.insert(END,"\n") 
 
scores = Tk()  
label = Label(scores, text="High Scores", font = ("Arial",30)).grid(row = 0, columnspan = 3) 
listBox= Text(scores,width = 40) 
listBox.grid(row = 1,column= 0, columnspan = 2) 
showScores = Button(scores, text = "Show scores",width = 15, command = show).grid(row = 4, column = 0) 
closeButton = Button(scores, text = "Close",width = 15, command = exit).grid(row = 4, column = 1) 
 
scores.mainloop() 

请您参考如下方法:

没有树部分的 ttk.Treeview 可用于显示表格:

tree = ttk.Treeview(master, columns=('Position', 'Name', 'Score'), show='headings') 

然后设置列标签

tree.heading(<column>, text="Label") 

并添加行

tree.insert("", "end", values=(<position>, <name>, <score>)) 

第一个参数是项目的父级,因为您需要一个表,所以所有项目都有相同的父级,即根 ""。第二个参数是新项目在树中的位置。

完整示例:

import tkinter as tk 
from tkinter import ttk 
 
def show(): 
 
    tempList = [['Jim', '0.33'], ['Dave', '0.67'], ['James', '0.67'], ['Eden', '0.5']] 
    tempList.sort(key=lambda e: e[1], reverse=True) 
 
    for i, (name, score) in enumerate(tempList, start=1): 
        listBox.insert("", "end", values=(i, name, score)) 
 
scores = tk.Tk()  
label = tk.Label(scores, text="High Scores", font=("Arial",30)).grid(row=0, columnspan=3) 
# create Treeview with 3 columns 
cols = ('Position', 'Name', 'Score') 
listBox = ttk.Treeview(scores, columns=cols, show='headings') 
# set column headings 
for col in cols: 
    listBox.heading(col, text=col)     
listBox.grid(row=1, column=0, columnspan=2) 
 
showScores = tk.Button(scores, text="Show scores", width=15, command=show).grid(row=4, column=0) 
closeButton = tk.Button(scores, text="Close", width=15, command=exit).grid(row=4, column=1) 
 
scores.mainloop() 

您可以找到有关 Treeview 小部件的更多详细信息 here .