ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

python – Tkinter.PhotoImage不支持png图像

2019-09-18 20:51:40  阅读:201  来源: 互联网

标签:tk python linux tkinter


我正在使用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),它一直都失败了.

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(), 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

标签:tk,python,linux,tkinter
来源: https://codeday.me/bug/20190918/1811456.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有