【问题标题】:Using PIL ImageTk.PhotoImage results in error "'PhotoImage' object has no attribute '_PhotoImage__photo'"使用 PIL ImageTk.PhotoImage 会导致错误“'PhotoImage' 对象没有属性 '_PhotoImage__photo'”
【发布时间】:2022-02-17 23:16:11
【问题描述】:

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

render = ImageTk.PhotoImage(Image.open(pic))

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

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'

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

【问题讨论】:

  • 不知道为什么你正在做的事情不起作用。试试render = ImageTk.PhotoImage(image=Image.open(pic))render = ImageTk.PhotoImage(file=pic)(假设pic 是一个文件名)。
  • 谢谢。回答,但我已经尝试了这两个结果相同的错误
  • 当一切都失败时,尝试重新安装 PIL/Pillow。
  • 已经尝试重新安装,也可以使用不同的版本。但同样的错误

标签: python python-imaging-library


【解决方案1】:

使用 ImageTk module 取决于 Tkinter 实例,因为 ImageTk.PhotoImage 旨在“在 Tkinter 期望图像对象的任何地方使用”。

从 Traceback 来看,PhotoImage 基本上只是调用了 Tkinter 的 PhotoImage 构造函数:

self.__photo = tkinter.PhotoImage(**kw)

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

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 中,它只是忽略了那个错误(“Exception被忽略在:...”),所以 PhotoImage 的其余部分创建失败并出现你得到的错误。

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

先尝试创建一个 Tkinter 实例:

from PIL import ImageTk, Image
from tkinter import Tk

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

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

【讨论】:

  • 感谢您的评论。我有file=image,但没有用。
  • 太好了,这就是我的解决方案```为了解决这个问题,必须正确初始化 Tkinter 部分。首先尝试创建一个 Tkinter 实例:```
【解决方案2】:
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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-19
    • 2021-09-05
    • 2023-02-02
    • 1970-01-01
    • 1970-01-01
    • 2019-12-23
    相关资源
    最近更新 更多