我尝试了两种不同的方法来尝试让图像显示在标签中
#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)
图像与所有代码位于同一文件夹中。关于如何显示图像有什么建议吗?
最佳答案
Bryan Oakley 是正确的,图像在内容方面不是 jpg,即使您的文件系统认为它是 gif。
在我这边,我尝试用你的程序打开一个 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)
)
关于python - Tkinter 图像不显示或出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15718663/