9

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?

Arktri
  • 577
  • 2
  • 6
  • 9
  • 2
    The first seems to be giving you useful information. Are you certain the image is a proper .gif? – Bryan Oakley Mar 30 '13 at 13:50
  • It was a jpeg that I saved as a .gif (Type says GIF File). So I'm assuming that's alright. – Arktri Mar 30 '13 at 13:53
  • 2
    no, that's not alright. Tkinter only supports files in the GIF format, no matter what the name is. Simply changing the name doesn't automatically make it a GIF. To display jpeg you'll need to use PIL. – Bryan Oakley Mar 30 '13 at 17:42
  • So even though it's file type is .gif and it only opens in browsers, it's still not a gif? – Arktri Mar 30 '13 at 20:05
  • 1
    Correct. The filename is unimportant. Browsers have support for many file types that Tkinter does not. – Bryan Oakley Mar 30 '13 at 21:08
  • http://i.imgur.com/8nHaRCL.png This is the image I am trying to use. Not the imgur picture but the .gif in the folder screenshot. TestImage. – Arktri Mar 30 '13 at 23:33

1 Answers1

7

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))

twasbrillig
  • 17,084
  • 9
  • 43
  • 67