How do I use tkinter 'Treeview' to list items in a table of a database?

Cameron Hamilton picture Cameron Hamilton · Nov 27, 2017 · Viewed 8.8k times · Source

I have a SQLite database that I am going to read from and list one of its tables data into a tree view. I have been searching for a long time in order to get this to work and I am struggling to find anything that either works or makes sense to me. for instance in my table I have the headings 'Member ID' and 'Full Name'.

for test purposes I have created variables storing strings for these values.

root = Tk()

name = "cameron"
id="223344"

lblsearchName = Label(root, text="Full Name:")
lblsearchName.grid(sticky=E)
searchEntry = Entry(root)
searchEntry.grid(column=1, sticky=E)

treeView = ttk.Treeview(root)
treeView.grid(columnspan=2)

root.mainloop()

How do I go about creating headings in the treeview according to the headings in my tables of my database? I now how to read for the database but I then need to know how I would insert this values into the treeview. (for this example 'name' and 'id')

Answer

Roars picture Roars · Nov 27, 2017
# set up the columns and headings
# In reality "Member ID" would be exported from the database
treeview["columns"] = ["Member ID", "Full Name"]
treeview["show"] = "headings"
treeview.heading("Member ID", text="Member ID")
treeview.heading("Full Name", text="Full Name")

# Add content using (where index is the position/row of the treeview)
# iid is the item index (used to access a specific element in the treeview)
# you can set iid to be equal to the index
tuples = [(1, "Name1"),(2, "Name2")]
index = iid = 0
for row in tuples:
    treeView.insert("", index, iid, values=row)
    index = iid = index + 1

Sample output:

screenshot showing output code creates

More information on heading.

More information on insert.

More information on options (E.g. columns and headings)