【发布时间】: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