【问题标题】:Opening an image using ImageTk in Pillow causing an AttributeError and RuntimeError?在 Pillow 中使用 ImageTk 打开图像会导致 AttributeError 和 RuntimeError?
【发布时间】:2020-06-25 21:54:34
【问题描述】:

我在 Python 3.8.2 中使用 Pillow 7.1.2。我在使用 Image.open 和 ImageTk.PhotoImage 方法打开图像以在 Tkinter 程序中使用时遇到问题。这是我能想到的最简单的导入图像的方法,我已经将这些图像写入了我的暂存文件,我得到了一个 AttributeError 和一个 RuntimeError。

from PIL import Image, ImageTk

image = Image.open("0.gif")
photo = ImageTk.PhotoImage(image)

就我能找到的所有资源而言,这段代码应该可以工作,但不能。我错过了一些非常明显的东西吗?错误如下:

Traceback (most recent call last):
  File "C:/Users/cassi/AppData/Roaming/JetBrains/PyCharmEdu2020.1/scratches/scratch.py", line 4, in <module>
    photo = ImageTk.PhotoImage(image)
  File "C:\Users\cassi\PycharmProjects\Temp\venv\lib\site-packages\PIL\ImageTk.py", line 112, in __init__
    self.__photo = tkinter.PhotoImage(**kw)
  File "C:\Program Files\Python38\lib\tkinter\__init__.py", line 4061, in __init__
    Image.__init__(self, 'photo', name, cnf, master, **kw)
  File "C:\Program Files\Python38\lib\tkinter\__init__.py", line 3994, in __init__
    raise RuntimeError('Too early to create image')
RuntimeError: Too early to create image
Exception ignored in: <function PhotoImage.__del__ at 0x000001ADDF06B5E0>
Traceback (most recent call last):
  File "C:\Users\cassi\PycharmProjects\Temp\venv\lib\site-packages\PIL\ImageTk.py", line 118, in __del__
    name = self.__photo.name
AttributeError: 'PhotoImage' object has no attribute '_PhotoImage__photo'

我将如何解决这个问题?我的代码有问题,还是其他问题?谢谢!

【问题讨论】:

  • 在您致电 Tk() 之前,您无法创建 PhotoImages。直到那时,图像将存在的环境甚至都不存在。
  • 本网站上有近两打与该确切错误相关的问题。这些都没有帮助你回答你的问题吗?这个问题与那些问题有何不同?

标签: python python-3.x tkinter python-imaging-library


【解决方案1】:

像这样:

from tkinter import *
from PIL import Image, ImageTk

canvas = Canvas(Tk(),width=200,height=200)
canvas.pack()

image = Image.open("0.gif") # Convert to PIL image

pimage = ImageTk.PhotoImage(image) # Convert to PhotoImage

canvas.create_image(100,100,image=pimage)

【讨论】:

    【解决方案2】:

    tkinter 在创建 ImageTk.PhotoImage 对象之前没有创建窗口(@98​​7654323@ 对象)时会引发错误。 试试这个代码,它的工作原理:

    from PIL import Image, ImageTk
    import tkinter 
    #don't use "from tkinter import *" because tkinter also has an Image object and things will get mixed up
    window = tkinter.Tk()
    #Now you can create an Photo Image in PIL
    img = Image.open("0.gif")
    tkimg = ImageTk.PhotoImage(img)
    label1 = tkinter.Label(window, image = tkimg)
    label1.pack()
    

    如果这也不起作用,也许你只是下载了一个 e. '0.jpg' 图片并将其重命名为 '0.gif'。 Here's the link 在线转换为 .gif 或这里是 PIL 代码:

    from PIL import Image
    img = Image.open("0.jpg")
    img.save("0.gif", "gif") # Signature of function: Image().save(name, type)
    

    【讨论】:

    • @Cassidy 如果这不起作用,请留下您的操作系统名称和 python 版本,以便我可以尝试另一个答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-23
    • 2019-08-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多