Kai*_*Kai 1 python python-imaging-library
我正在尝试使用 PIL 版本 6.2.1 在 python 3.7.3 中执行以下代码:
render = ImageTk.PhotoImage(Image.open(pic))
Run Code Online (Sandbox Code Playgroud)
但它会导致如下错误消息:
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'
Run Code Online (Sandbox Code Playgroud)
我尝试了不同的 Pillow 版本,尝试按照其他帖子的建议输入类实例,尝试使用os.chdir(pic_dir). 但它们都不起作用。
使用ImageTk 模块取决于 Tkinter 实例,因为ImageTk.PhotoImage它被设计为“在 Tkinter 需要图像对象的任何地方使用”。
从 Traceback 来看,PhotoImage基本上只是调用 Tkinter 的 PhotoImage 构造函数:
self.__photo = tkinter.PhotoImage(**kw)
Run Code Online (Sandbox Code Playgroud)
然后是检查正在运行的 Tkinter 实例的基类:PhotoImage
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')
Run Code Online (Sandbox Code Playgroud)
由于它找不到,它会引发“创建图像太早”错误。然后在 PIL 中,它只是忽略该错误(“ Exception returned in:... ”),因此其余的创建会PhotoImage失败并出现您收到的错误。
为了解决这个问题,Tkinter 部件必须正确初始化。
首先尝试创建一个 Tkinter 实例:
from PIL import ImageTk, Image
from tkinter import Tk
root = Tk()
render = ImageTk.PhotoImage(image=Image.open("sample.jpg"))
Run Code Online (Sandbox Code Playgroud)
或者使用Image不依赖于 Tkinter 的通用模块。
| 归档时间: |
|
| 查看次数: |
3242 次 |
| 最近记录: |