python的ImageTk.PhotoImage坑怎么解决

发布时间:2022-12-01 10:12:00 作者:iii
来源:亿速云 阅读:133

这篇文章主要介绍“python的ImageTk.PhotoImage坑怎么解决”,在日常操作中,相信很多人在python的ImageTk.PhotoImage坑怎么解决问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”python的ImageTk.PhotoImage坑怎么解决”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

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 &lsquo;numpy.ndarray&rsquo;>类型

所以,大坑来了

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

可以这样改:

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

Tkinter PhotoImage 踩坑记录

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

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

解决办法:使用PILLOW库的ImageTk

代码:

from PIL import Image

from PIL import ImageTk

img = Image.open(filePath)

img = ImageTk.PhotoImage(img)

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

原因:说白了就是图像数据引用被回收了图片就显示不出来了,只会显示一个空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

到此,关于“python的ImageTk.PhotoImage坑怎么解决”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!

推荐阅读:
  1. addView遇到的坑及其解决
  2. python中ImageTk.PhotoImage()不显示图片却不报错问题解决

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python imagetk.photoimage

上一篇:Python怎么实现在字典中获取带权重的随机值

下一篇:MySQL存储过程基本语法是什么

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》