Last updated: Apr 11, 2024
Reading time·2 min

The tkinter "TclError: couldn't recognize data in image file" occurs when you
try to create an image from an unsupported file type, e.g. jpg or jpeg.
To solve the error, use a .png or a .gif image or use the Pillow library
when loading the image.

Here is an example of how the error occurs.
from tkinter import * root = Tk() canv = Canvas(root, width=500, height=500, bg='white') canv.grid(row=2, column=3) # ⛔️ _tkinter.TclError: couldn't recognize data in image file "house.jpg" img = PhotoImage(file="house.jpg") canv.create_image(0, 0, anchor=NW, image=img) root.mainloop()
Notice that we tried to pass a jpg image to the PhotoImage() class.
Using jpg images is not supported which caused the error.
One way to get around this is to use a .png or .gif image file.
Here is an example of using a .png image instead.
from tkinter import * root = Tk() canv = Canvas(root, width=500, height=500, bg='white') canv.grid(row=2, column=3) # ✅ Changed the image to .png img = PhotoImage(file="house.png") canv.create_image(0, 0, anchor=NW, image=img) root.mainloop()

Everything works as expected when using a supported image type (e.g. .png or
.gif).
In theory, PNG support is dependent on the system's version of Tcl/Tk which is a
library Python interfaces with through Tkinter, however, I haven't run into any
issues when using .png files.
To be on the safe side, you might want to use the PhotoImage class from the
Pillow library as shown in the next subheading.
Pillow library when loading the imageAlternatively, you can use the Pillow library when loading the image.
First, make sure to install Pillow.
pip install Pillow # Or with pip3 pip3 install Pillow
Now import and use the module as follows.
from tkinter import * from PIL import ImageTk, Image root = Tk() canv = Canvas(root, width=500, height=500, bg='white') canv.grid(row=2, column=3) # 👇️ can now use a .jpg file img = ImageTk.PhotoImage(Image.open('house.jpg')) canv.create_image(0, 0, anchor=NW, image=img) root.mainloop()
We imported the ImageTk and Image modules from PIL.
Instead of using the PhotoImage class from tkinter, we now use the class
from the ImageTk module.
The ImageTk.PhotoImage class is a tkinter-compatible photo image.
The class can be used everywhere tkinter expects an image object.
The constructor expects to get called with a PIL image or a mode string.
The Image.open() method opens and identifies the given image file.
The method supports various file types, including images with .jpg extension.
Everything else in the code sample can remain the same.
The PhotoImage class from the tkinter module supports .gif files
regardless of the Tcl/Tk version and .png files for most Tcl/Tk versions.
There are also plans to also add support for .svg images.
You can learn more about the related topics by checking out the following tutorials: