我编写了一个程序,它从文本文件中获取数据并以表格样式显示。
来自文本文件的数据:
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()
答案 0 :(得分:3)
没有树部分的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的更多详细信息。
答案 1 :(得分:-1)
from tkinter import *
from pandastable import Table
root = Tk()
frame = Frame(root)
frame.pack()
pt = Table(frame)
pt.show()
root.mainloop()