ttk.Treeview – Insert a row with a JPG 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
28
29
30
31
32
33
import tkinter as tk
from tkinter import ttk
from PIL import Image, ImageTk


root = tk.Tk()

# Load the JPG file
img_house = Image.open(r"images/house.jpg")

# Convert the JPG image to a PhotoImage instance that tkinter can use.
image_tk = ImageTk.PhotoImage(img_house)

# Define columns
column_names = ("dwelling_type_column", "location_column")

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

# Create the column texts that the user will see.
treeview_places.heading("dwelling_type_column", text="Dwelling Type")
treeview_places.heading("location_column", text="Location")


treeview_places.insert(parent="",
                     index="end",
                     image=image_tk,
                     values=("House", "Fantasy Land"))


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

root.mainloop()

We have to use the PIL module to load a JPG image and convert it to a PhotoImage instance that tkinter can use. Tkinter supports PNG without the need to use PIL, but for JPG we have to use PIL.