经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » Python » 查看文章
python的ImageTk.PhotoImage大坑及解决
来源:jb51  时间:2022/12/2 10:58:45  对本文有异议

python的ImageTk.PhotoImage大坑

如果大家遇到这样的报错:

Exception in Tkinter callback
Traceback (most recent call last):
  File "E:\Anaconda3_files\lib\site-packages\PIL\Image.py", line 2515, in fromarray
    mode, rawmode = _fromarray_typemap[typekey]
KeyError: ((1, 1, 3), '<f8')

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "E:\Anaconda3_files\lib\tkinter\__init__.py", line 1705, in __call__
    return self.func(*args)
  File "D:\Junior Spring\Digital Image Processing and Experiment\数字实验备份\结课实验\ImgProcessing.py", line 806, in Sobel_Sharpening
    image = ImageTk.PhotoImage(Image.fromarray(img))
  File "E:\Anaconda3_files\lib\site-packages\PIL\Image.py", line 2517, in fromarray
    raise TypeError("Cannot handle this data type")
TypeError: Cannot handle this data type

网上很多教程的方法我也试过,没有用,也调试不出为什么

这里有个很关键的信息:Cannot handle this data type

说明是数据的类型错了,但再三检查后,明明就是带入的<class ‘numpy.ndarray’>类型

所以,大坑来了

请仔细检查自己array里面每个数的类型,它必须是<class ‘numpy.uint8’>,否则就会报错

可以这样改:

  1. dst = dst.astype(np.uint8)
  2. image = ImageTk.PhotoImage(Image.fromarray(dst))

Tkinter PhotoImage 踩坑记录

1.直接使用PhotoImage(file= ‘xxxx’)报错:_tkinter.TclError: couldn’t recognize data in image file “xxxxx.png”

原因:PhotoImage支持的图片格式有限。

解决办法:使用PILLOW库的ImageTk

  • 1.如果没有安装PILLOW插件,请安装插件,使用 “pip install PILLOW”命令安装即可
  • 2.生成PhotoImage对象:

代码:

  1. from PIL import Image
  2.  
  3. from PIL import ImageTk
  4.  
  5. img = Image.open(filePath)
  6.  
  7. img = ImageTk.PhotoImage(img)

2.PhotoImage显示问题:显示空白框,大小是图片的真实大小

原因:见https://docs.Python.org/2/library/tkinter.html#images,说白了就是图像数据引用被回收了图片就显示不出来了,只会显示一个空box。

解决办法:保存PhotoImage对象即可,示例代码如下:

代码:

  1. imgDict = {}
  2. def getImgWidget(filePath):
  3.  
  4. ? ? if os.path.exists(filePath) and os.path.isfile(filePath):
  5.  
  6. ? ? ? ? if filePath in imgDict and imgDict[filePath]:
  7.  
  8. ? ? ? ? ? ? return imgDict[filePath]
  9.  
  10. ? ? ? ? img = Image.open(filePath)
  11.  
  12. ? ? ? ? #print(img.size)
  13.  
  14. ? ? ? ? img = ImageTk.PhotoImage(img)
  15.  
  16. ? ? ? ? imgDict[filePath] = img
  17.  
  18. ? ? ? ? return img
  19.  
  20. ? ? return None

以上为个人经验,希望能给大家一个参考,也希望大家多多支持w3xue。

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号