What is the best way to show data in a table in Tkinter?

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()

screenshot

You can find more details about the Treeview widget here.

Leave a Comment