Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tkinter error: Couldn't recognize data in image file

I'm trying to put a jpg image to a tkinter canvas. tkinter gives me this error:

couldn't recognize data in image file

I use the code from the documentation:

canv = Canvas(root, width=80, height=80, bg='white')
canv.grid(row=2, column=3)

img = PhotoImage(file="bll.jpg")
canv.create_image(20,20, anchor=NW, image=img)

Same thing with png images. Even tried to put an image into a label widget, but got the same error. What's wrong?

I am using Python 3 on Mac. Python file and image are in the same folder.

like image 403
Igor234 Avatar asked Nov 17 '17 18:11

Igor234


People also ask

Does tkinter recognize JPG?

Tkinter PhotoImage file formats Currently, the PhotoImage widget supports the GIF, PGM, PPM, and PNG file formats as of Tkinter 8.6. To support other file formats such as JPG, JPEG, or BMP, you can use an image library such as Pillow to convert them into a format that the PhotoImage widget understands.

Can tkinter display images?

Tkinter's label widget can be used to display either images or text. To display an image requires the use of Image and ImageTk imported from the Python Pillow (aka PIL) package.

Why is my tkinter not working?

In conclusion, if the error no module named tkinter raises, it probably means you are using python 2. Firstly, you can get around the problem by upgrading to python 3. Additionally, you can rename your import to Tkinter , which is how the module was named in python 2, just if upgrading is not an option.


1 Answers

Your code seems right, this is running for me on Windows 7 (Python 3.6):

from tkinter import *
root = Tk()

canv = Canvas(root, width=80, height=80, bg='white')
canv.grid(row=2, column=3)

img = PhotoImage(file="bll.jpg")
canv.create_image(20,20, anchor=NW, image=img)

mainloop()

resulting in this tkinter GUI:

GUI with this image as bll.jpg: image

(imgur converted it to bll.png but this is working for me as well.)


More options:

  • This answer mentions, tkinter is working only with gif images. Try using a .gif image.
  • If this is not working, use PIL as stated in this answer.

Update: Solution with PIL:

from tkinter import *
from PIL import ImageTk, Image
root = Tk()

canv = Canvas(root, width=80, height=80, bg='white')
canv.grid(row=2, column=3)

img = ImageTk.PhotoImage(Image.open("bll.jpg"))  # PIL solution
canv.create_image(20, 20, anchor=NW, image=img)

mainloop()
like image 107
bastelflp Avatar answered Sep 16 '22 15:09

bastelflp