我正在使用 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 许可协议
tkinter 仅支持 3 种文件格式,即 GIF、PGM 和 PPM。您要么需要将文件转换为 .GIF 然后加载它们(要容易得多,但正如 jonrsharpe 所说,如果不先转换文件,什么都不会起作用),或者您可以将程序移植到 Python 2.7 并使用 Python Imaging Library (PIL)及其 tkinter 扩展以使用 PNG 图像。
您可能会发现有用的链接:http: //effbot.org/tkinterbook/photoimage.htm