【问题标题】:Tkinter image not showing or giving an errorTkinter 图像未显示或出现错误
【发布时间】:2013-03-21 01:33:09
【问题描述】:

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

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

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

【问题讨论】:

  • 第一个似乎给你有用的信息。您确定图片是正确的 .gif 文件吗?
  • 这是我保存为 .gif 的 jpeg(类型为 GIF 文件)。所以我假设没关系。
  • 不,这样不行。 Tkinter 只支持 GIF 格式的文件,不管名字是什么。简单地更改名称不会自动使其成为 GIF。要显示 jpeg,您需要使用 PIL。
  • 所以即使它的文件类型是 .gif 并且只在浏览器中打开,它仍然不是 gif?
  • 正确。文件名不重要。浏览器支持许多 Tkinter 不支持的文件类型。

标签: python user-interface tkinter


【解决方案1】:

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)

【讨论】:

    猜你喜欢
    • 2020-11-04
    • 2021-05-11
    • 1970-01-01
    • 1970-01-01
    • 2022-12-16
    • 2023-02-21
    • 1970-01-01
    • 1970-01-01
    • 2018-04-25
    相关资源
    最近更新 更多