ttk.Treeview – Creating columns

Screenshot of final result:

img

Let’s start with this snippet of code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
import tkinter as tk
from tkinter import ttk


root = tk.Tk()

# Define columns. These names will not be shown to the user.
# These are only the column names that we will reference in our code.
column_names = ("Make", "Year", "Colour")

# Pass the column names when we make the treeview.
treeview_cars = ttk.Treeview(root, columns=column_names)

# At this point, the columns will show in the treeview, but the
# columns will have no text.

# That’s because we’ve created the columns by giving 
# them names, but we haven’t given them any text.
treeview_cars.pack(expand=True, fill=tk.BOTH)

root.mainloop()

Which gives us:

img So now we have a treeview with 3 columns (technically 4 columns if we count the first tree column). However, the columns don’t have any text so far.

You can also create the columns later in your code, like this:

column_names = ("Make", "Year", "Colour")
treeview_cars[columns] = column_names

Or by using the configure method like this: (In my opinion this is the cleanest way)

column_names = ("Make", "Year", "Colour")
treeview_cars.configure(columns=column_names)

To set the text of the columns, use the heading() method:

column_names = ("Make", "Year", "Colour")
treeview_cars.heading("Make", text="The Make of the car")

You can pass the column name, or column index (starting with index 0).

Index 0 is the first non-image column.

However, there is another column before index 0, called #0

img

Column #0 (zero, not the letter O), is a special tree column. The name “#0” is automatically chosen by tkinter itself for the tree column. “#0” should be passed as a string, not an integer.

You can set the text for each column like this:

treeview_cars.heading("#0", text="Car Photo")
treeview_cars.heading(0, text="The Make of the car")
treeview_cars.heading(1, text="Year Built")
treeview_cars.heading(2, text="Car Colour")

img

You may also use the column names instead of column indexes. This will give you the same result.

treeview_cars.heading("#0", text="Car Photo")
treeview_cars.heading("Make", text="The Make of the car")
treeview_cars.heading("Year", text="Year Built")
treeview_cars.heading("Colour", text="Car Colour")