Tkinter 图像未显示或出现错误 [英] Tkinter image not showing or giving an error

查看:24
本文介绍了Tkinter 图像未显示或出现错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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)

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

推荐答案

Bryan Oakley 是正确的,就其内容而言,图像不是 jpg,即使您的文件系统认为它是 gif.

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

最后,我尝试用你的程序打开一个 jpg,但得到同样的错误TclError:无法识别图像文件hello.jpg"中的数据.'

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".'

所以你可以这样做:用mspaint打开你的图像,然后去文件>另存为,从另存为类型"下拉菜单中,选择GIF.然后代码应该可以工作.这是我用的:

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

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

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

这篇关于Tkinter 图像未显示或出现错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆