ttk.Treeview – Insert a row with a PNG image

The treeview widget can show an image in the first column, for each row. The first column in a treeview is referenced with the name #0 (the tree column) and is the only column that can hold an image.

We can achieve this:

img

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import tkinter as tk
from tkinter import ttk, PhotoImage


root = tk.Tk()

# PNG image path
img_canada_flag = PhotoImage(file=r"images/canada_flag.png")

# Define columns
column_names = ("country_column", "capital_city_column")

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

# Create the column texts that the user will see.
treeview_country.heading("country_column", text="Country")
treeview_country.heading("capital_city_column", text="Capital")

treeview_country.insert(parent="",
                     index="end",
                     image=img_canada_flag,
                     values=("Canada", "Ottawa"))

treeview_country.pack(expand=True, fill=tk.BOTH)

root.mainloop()

Tkinter natively supports PNG images. We don’t need to use the PIL module to add PNG images to a treeview. However, JPG images will need the use of PIL.

We can improve this program a bit. Notice the gap between the image column (‘#0’) and the Country column (‘country_column’)

img

We can fix that by specifying the width of the image column:

treeview_country.column("#0", width=75)

Now the image column is closer to the country column.

img