首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用PIL对象会导致错误"'PhotoImage‘ImageTk.PhotoImage has no attribute '_PhotoImage__photo'“

使用PIL对象会导致错误"'PhotoImage‘ImageTk.PhotoImage has no attribute '_PhotoImage__photo'“
EN

Stack Overflow用户
提问于 2019-12-29 08:35:15
回答 2查看 1.4K关注 0票数 1

我尝试在python 3.7.3中使用PIL版本6.2.1编写以下代码:

代码语言:javascript
复制
render = ImageTk.PhotoImage(Image.open(pic))

但它会导致如下所示的错误消息:

代码语言:javascript
复制
Traceback (most recent call last):
  File "F:/python/test/test10.py", line 12, in <module>
    render = ImageTk.PhotoImage(Image.open(pic))
  File "C:\Users\erica\AppData\Roaming\Python\Python37\site-packages\PIL\ImageTk.py", line 118, in __init__
    self.__photo = tkinter.PhotoImage(**kw)
  File "C:\Users\erica\AppData\Local\Programs\Python\Python37\lib\tkinter\__init__.py", line 3545, in __init__
    Image.__init__(self, 'photo', name, cnf, master, **kw)
  File "C:\Users\erica\AppData\Local\Programs\Python\Python37\lib\tkinter\__init__.py", line 3489, in __init__
    raise RuntimeError('Too early to create image')
RuntimeError: Too early to create image
Exception ignored in: <function PhotoImage.__del__ at 0x0000027A91FEB0D0>
Traceback (most recent call last):
  File "C:\Users\erica\AppData\Roaming\Python\Python37\site-packages\PIL\ImageTk.py", line 124, in __del__
    name = self.__photo.name
AttributeError: 'PhotoImage' object has no attribute '_PhotoImage__photo'

我尝试过不同的枕头版本,尝试按照其他帖子的建议输入类实例,尝试使用os.chdir(pic_dir)。但它们都不起作用。

EN

回答 2

Stack Overflow用户

发布于 2019-12-29 21:47:15

使用ImageTk module依赖于Tkinter实例,因为ImageTk.PhotoImage被设计为“在Tkinter期望图像对象的任何地方使用”。

在回溯过程中,PhotoImage基本上只是调用Tkinter的PhotoImage构造函数:

代码语言:javascript
复制
self.__photo = tkinter.PhotoImage(**kw)

然后,base class for PhotoImage检查正在运行的Tkinter实例:

代码语言:javascript
复制
def __init__(self, imgtype, name=None, cnf={}, master=None, **kw):
    self.name = None
    if not master:
        master = _default_root
        if not master:
            raise RuntimeError('Too early to create image')

由于没有找到镜像,它会抛出“创建镜像太早了”的错误。然后在PIL中,它只是忽略这个错误(“在以下位置忽略异常:...”)因此,创建PhotoImage的其余部分将失败,并显示您收到的错误。

要解决此问题,必须正确初始化Tkinter部分。

先尝试创建一个Tkinter实例:

代码语言:javascript
复制
from PIL import ImageTk, Image
from tkinter import Tk

root = Tk()
render = ImageTk.PhotoImage(image=Image.open("sample.jpg"))

或者使用不依赖于Tkinter的通用Image模块。

票数 4
EN

Stack Overflow用户

发布于 2022-02-17 13:42:49

代码语言:javascript
复制
self.img = ImageTk.PhotoImage(Image.open("yourimage.png")) # photoimage attribute error .......
img = Label(self.root,image = self.img).place(x=0,y=0,relheight=1,relwidth=1)
#love man
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59516051

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档