在tkinter中使用PIL显示图片时,提示AttributeError: 'PhotoImage' object has no attribute '_PhotoImage__photo',最后发现原因是应为PhotoImage本质上是调用TKinter的PhotoImage构造函数,所以在使用之前需要先初始化Tk()
为什么说是原因1呢,因为导致AttributeError的原因有很多,后续遇到会在记录下来的。
示例
错误:
import tkinter as tk
from PIL import ImageTk,Image
p = Image.open(r"E:\项目更新\hypergryphTool\sc\zhyd.png")
imager = ImageTk.PhotoImage(p)
root = tk.Tk()
a = tk.Label(root,image=imager)
a.pack()
root.mainloop()
Traceback (most recent call last):
File "C:/Users/admin/PycharmProjects/pythonProject/main.py", line 7, in
imager = ImageTk.PhotoImage(p)
File "C:\Users\admin\AppData\Local\Programs\Python\Python38\lib\site-packages\PIL\ImageTk.py", line 112, in __init__
self.__photo = tkinter.PhotoImage(**kw)
File "C:\Users\admin\AppData\Local\Programs\Python\Python38\lib\tkinter\__init__.py", line 4064, in __init__
Image.__init__(self, 'photo', name, cnf, master, **kw)
File "C:\Users\admin\AppData\Local\Programs\Python\Python38\lib\tkinter\__init__.py", line 3997, in __init__
master = _get_default_root('create image')
File "C:\Users\admin\AppData\Local\Programs\Python\Python38\lib\tkinter\__init__.py", line 297, in _get_default_root
raise RuntimeError(f"Too early to {what}: no default root window")
RuntimeError: Too early to create image: no default root window
Exception ignored in:
Traceback (most recent call last):
File "C:\Users\admin\AppData\Local\Programs\Python\Python38\lib\site-packages\PIL\ImageTk.py", line 118, in __del__
name = self.__photo.name
AttributeError: 'PhotoImage' object has no attribute '_PhotoImage__photo'
Process finished with exit code 1
正确写法:
import tkinter as tk
from PIL import ImageTk,Image
root = tk.Tk()
p = Image.open(r"E:\项目更新\hypergryphTool\sc\zhyd.png")
imager = ImageTk.PhotoImage(p)
a = tk.Label(root,image=imager)
a.pack()
root.mainloop()
结果: