Tkinter.PhotoImage 不支持 png 图片

新手上路,请多包涵

我正在使用 Tkinter 编写 GUI,并希望在 Tkiner.Label 中显示 png 文件。所以我有一些这样的代码:

 self.vcode.img = PhotoImage(data=open('test.png').read(), format='png')
self.vcode.config(image=self.vcode.img)

此代码 在我的 Linux 机器上正确运行。但是当我在我的 Windows 机器上运行它时,它失败了。我还在其他几台机器(包括windows和linux)上进行了测试,它一直失败。

回溯是:

 Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Python27\lib\lib-tk\Tkinter.py", line 1486, in __call__
    return self.func(*args)
  File "C:\Documents and Settings\St\client\GUI.py", line 150, in showrbox
    SignupBox(self, self.server)
  File "C:\Documents and Settings\St\client\GUI.py", line 197, in __init__
    self.refresh_vcode()
  File "C:\Documents and Settings\St\client\GUI.py", line 203, in refresh_vcode
    self.vcode.img = PhotoImage(data=open('test.png').read(), format='png')
  File "C:\Python27\lib\lib-tk\Tkinter.py", line 3323, in __init__
    Image.__init__(self, 'photo', name, cnf, master, **kw)
  File "C:\Python27\lib\lib-tk\Tkinter.py", line 3279, in __init__
   self.tk.call(('image', 'create', imgtype, name,) + options)
TclError: image format "png" is not supported

如果我删除源代码中的 format='png' ,回溯会变成:

 Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Python27\lib\lib-tk\Tkinter.py", line 1486, in __call__
    return self.func(*args)
  File "C:\Documents and Settings\St\client\GUI.py", line 150, in showrbox
    SignupBox(self, self.server)
  File "C:\Documents and Settings\St\client\GUI.py", line 197, in __init__
    self.refresh_vcode()
  File "C:\Documents and Settings\St\client\GUI.py", line 203, in refresh_vcode
    self.vcode.img = PhotoImage(data=open('test.png').read())
  File "C:\Python27\lib\lib-tk\Tkinter.py", line 3323, in __init__
    Image.__init__(self, 'photo', name, cnf, master, **kw)
  File "C:\Python27\lib\lib-tk\Tkinter.py", line 3279, in __init__
    self.tk.call(('image', 'create', imgtype, name,) + options)
TclError: couldn't recognize image data

那么,我应该怎么做才能让它支持 png 文件呢?

原文由 zsrkmyn 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.2k
2 个回答

tkinter 仅支持 3 种文件格式,即 GIF、PGM 和 PPM。您要么需要将文件转换为 .GIF 然后加载它们(要容易得多,但正如 jonrsharpe 所说,如果不先转换文件,什么都不会起作用),或者您可以将程序移植到 Python 2.7 并使用 Python Imaging Library (PIL)及其 tkinter 扩展以使用 PNG 图像。

您可能会发现有用的链接:http: //effbot.org/tkinterbook/photoimage.htm

原文由 Benjamin James Drury 发布,翻译遵循 CC BY-SA 3.0 许可协议

PIL 现在被枕头 http://pillow.readthedocs.io/en/3.2.x/ 取代

解决方案:

 from Tkinter import *
import PIL.Image
import PIL.ImageTk

root = Toplevel()

im = PIL.Image.open("photo.png")
photo = PIL.ImageTk.PhotoImage(im)

label = Label(root, image=photo)
label.image = photo  # keep a reference!
label.pack()

root.mainloop()


如果在代码中找不到 PIL ,您确实需要一个 pillow 安装:

 pip install pillow

原文由 HCLivess 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题