我尝试在python 3.7.3中使用PIL版本6.2.1编写以下代码:
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'我尝试过不同的枕头版本,尝试按照其他帖子的建议输入类实例,尝试使用os.chdir(pic_dir)。但它们都不起作用。
发布于 2019-12-29 21:47:15
使用ImageTk module依赖于Tkinter实例,因为ImageTk.PhotoImage被设计为“在Tkinter期望图像对象的任何地方使用”。
在回溯过程中,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中,它只是忽略这个错误(“在以下位置忽略异常:...”)因此,创建PhotoImage的其余部分将失败,并显示您收到的错误。
要解决此问题,必须正确初始化Tkinter部分。
先尝试创建一个Tkinter实例:
from PIL import ImageTk, Image
from tkinter import Tk
root = Tk()
render = ImageTk.PhotoImage(image=Image.open("sample.jpg"))或者使用不依赖于Tkinter的通用Image模块。
发布于 2022-02-17 13:42:49
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 manhttps://stackoverflow.com/questions/59516051
复制相似问题