Python Tkinter 图像未显示或出现错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15718663/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:45:56  来源:igfitidea点击:

Tkinter image not showing or giving an error

pythonuser-interfacetkinter

提问by Arktri

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?

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

回答by twasbrillig

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

Bryan Oakley 是正确的,就其内容而言,图像不是 jpg,即使您的文件系统认为它是 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".'

最后,我尝试用你的程序打开一个 jpg 并得到同样的错误“TclError:无法识别图像文件“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:

所以你可以这样做:用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()

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

(顺便说一句,如果我将上面的第 7 行更改为photo = PhotoImage(imgPath)像您一样,则不会出现图像。所以将其保留为photo = PhotoImage(file = imgPath)