Tkinter图像未显示或出错

时间:2013-03-30 12:45:30

标签: python user-interface tkinter

我尝试了两种不同的方法来尝试让图像显示在标签

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

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

图像与所有代码位于同一文件夹中。有关如何显示图像的任何建议吗?

1 个答案:

答案 0 :(得分:7)

Bryan Oakley是正确的,即使你的文件系统认为它是一个gif,图像的内容也不是jpg。

在我结束时,我尝试用你的程序打开一个jpg并得到同样的错误'TclError:无法识别图像文件中的数据“hello.jpg”。'

所以你可以这样做:用mspaint打开你的图像,然后转到文件>另存为,从“另存为类型”下拉列表中选择GIF。然后代码应该工作。这是我用过的:

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

(顺便说一句,如果我将上面的第7行更改为photo = PhotoImage(imgPath),那么就像你一样,不会出现任何图像。所以请保留为photo = PhotoImage(file = imgPath)