Tkinter image not showing or giving an error

后端 未结 1 1013
慢半拍i
慢半拍i 2020-12-10 15:20

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\"         


        
1条回答
  •  囚心锁ツ
    2020-12-10 15:40

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

    0 讨论(0)
提交回复
热议问题