python的ImageTk.PhotoImage大坑及解决

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

python的ImageTk.PhotoImage大坑及解决

_less is more   2022-11-30 我要评论

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’>,否则就会报错

可以这样改:

dst = dst.astype(np.uint8)
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对象:

代码:

from PIL import Image

from PIL import ImageTk

img = Image.open(filePath)

img = ImageTk.PhotoImage(img)

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

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

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

代码:

imgDict = {}
def getImgWidget(filePath):

    if os.path.exists(filePath) and os.path.isfile(filePath):

        if filePath in imgDict and imgDict[filePath]:

            return imgDict[filePath]

        img = Image.open(filePath)

        #print(img.size)

        img = ImageTk.PhotoImage(img)

        imgDict[filePath] = img

        return img

    return None

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

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们