Tkinter.PhotoImage不支持png图像

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

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

self.vcode.config(image=self.vcode.img)

这段代码

。但是,当我在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文件?

回答:

tkinter仅支持3种文件格式,即GIF,PGM和PPM。您可能需要将文件转换为.GIF然后加载它们(很容易,但正如jonrsharpe所说,如果不先转换文件就无法工作),也可以将程序移植到Python

2.7并使用Python Imaging Library(PIL)及其tkinter扩展以使用PNG图片。

您可能会发现有用的链接:http :

//effbot.org/tkinterbook/photoimage.htm

以上是 Tkinter.PhotoImage不支持png图像 的全部内容, 来源链接: utcz.com/qa/403894.html

回到顶部