I have written a program which takes data from a text file and displays it in a table style format.
Data from text file:
Jim,0.33
Dave,0.67
James,0.67
Eden,0.5
Formatted using the program:
Position | Name |Score
-----------------------------------
1 |Dave |0.67
2 |James |0.67
3 |Eden |0.5
4 |Jim |0.33
Without importing Pandas / SQL etc is there a better way of displaying this data?
The code I have written is below:
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()
A ttk.Treeview
without the tree part can be used to display a table:
tree = ttk.Treeview(master, columns=('Position', 'Name', 'Score'), show='headings')
Then set the column labels with
tree.heading(<column>, text="Label")
and add rows with
tree.insert("", "end", values=(<position>, <name>, <score>))
The first argument is the item's parent, since you want a table, all items have the same parent, the root ""
. The second argument is the position of the new item in the tree.
Full example:
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()
You can find more details about the Treeview
widget here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With