【发布时间】:2015-02-20 08:28:14
【问题描述】:
我正在使用 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',那么traceback会变成:
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 文件呢?
【问题讨论】:
-
您是否尝试过使用不同的文件格式?参见例如here.
-
@jonrsharpe,是的,我尝试过 'gif' 格式,它在我的 linux 机器上显示图像,但在我的 windows 机器上显示黑色(或白色或一些噪音)区域。
-
你用什么来转换图片的?它是否在
Tk应用程序外部的所有计算机上正确显示? -
@jonrsharpe,我没有使用任何东西来转换图像,它只是从互联网下载的图像。当然我测试了其他几个图像,都失败了。图像可以在
Tk应用程序外正确显示(在 windows 上使用“windows image andfax viewer”或在 linux 上使用“feh”)。 -
所以你只是告诉 tkinter 这是一个 gif 而它实际上仍然是一个 png?为什么你认为这会起作用?! 转换它。