Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tkinter image not showing or giving an error

I have tried two different things to try to get an image to show in a label

#This gives " TclError: couldn't recognize data in image file "TestImage.gif" "
imgPath = "TestImage.gif"
photo = PhotoImage(file = imgPath)
label = Label(image = photo)
label.image = photo # keep a reference!
label.grid(row = 3, column = 1, padx = 5, pady = 5)

and

#This gives no error but the image doesn't show
imgPath = "TestImage.gif"
photo = PhotoImage(imgPath)
label = Label(image = photo)
label.image = photo # keep a reference!
label.grid(row = 3, column = 1, padx = 5, pady = 5)

The image is in the same folder as all the code. Any suggestions on how to show an image?

like image 590
Arktri Avatar asked Mar 30 '13 12:03

Arktri


People also ask

Why does tkinter image not show up if created in a function?

The gist of it is that the image is passed by reference. If the reference is to a local variable, the memory referenced gets reused and the reference becomes stale. The variable storing the image should be in the same scope (has to have the same lifetime) as the Tk gui object it appears on.

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.

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

Bryan Oakley is correct, the image is not a jpg in terms of its content, even though your filesystem thinks it's a gif.

On my end I tried opening a jpg with your program and got the same error 'TclError: couldn't recognize data in image file "hello.jpg".'

So you can do this: Open your image with mspaint, then go to File > Save As and from the "Save As Type" dropdown, choose GIF. Then the code should work. This is what I used:

from Tkinter import *

root = Tk()

imgPath = r"hello.gif"
photo = PhotoImage(file = imgPath)
label = Label(image = photo)
label.image = photo # keep a reference!
label.grid(row = 3, column = 1, padx = 5, pady = 5)

root.mainloop()

(btw, if I changed line 7 above to photo = PhotoImage(imgPath) then like you, no image appears. So leave it as photo = PhotoImage(file = imgPath))

like image 170
twasbrillig Avatar answered Oct 13 '22 00:10

twasbrillig