使用TKInter python显示应该在表中的数据的最佳方法是什么

Neo*_*kia 1 python tkinter tabular

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

来自文本文件的数据:

Jim,0.33
Dave,0.67
James,0.67
Eden,0.5
Run Code Online (Sandbox Code Playgroud)

使用程序格式化:

Position | Name              |Score
-----------------------------------
1        |Dave               |0.67
2        |James              |0.67
3        |Eden               |0.5
4        |Jim                |0.33
Run Code Online (Sandbox Code Playgroud)

如果不导入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()
Run Code Online (Sandbox Code Playgroud)

j_4*_*321 5

ttk.Treeview没有树部分可被用于显示一个表:

tree = ttk.Treeview(master, columns=('Position', 'Name', 'Score'), show='headings')
Run Code Online (Sandbox Code Playgroud)

然后使用

tree.heading(<column>, text="Label")
Run Code Online (Sandbox Code Playgroud)

并添加行

tree.insert("", "end", values=(<position>, <name>, <score>))
Run Code Online (Sandbox Code Playgroud)

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

完整示例:

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()
Run Code Online (Sandbox Code Playgroud)

屏幕截图

您可以在此处找到有关Treeview小部件的更多详细信息。