python - 我只是想在 GUI 中显示图像。我究竟做错了什么?
问题描述
我正在尝试在 GUI 中显示图像,但不明白出了什么问题。我不断收到此错误:
AttributeError: 'PhotoImage' object has no attribute '_PhotoImage__photo'
我的代码(尤其是带有 的行my_img=...
)应该是什么样的?
我的代码:
from tkinter import *
from PIL import ImageTk,Image
my_img = ImageTk.PhotoImage(Image.open("iu.jpeg"))
my_label = Label(image=my_img)
my_label.pack()
root = Tk()
root.title("ICON PRACTICE")
root.iconbitmap('iu.ico')
button_quit = Button(root, text = "EXIT", command=root.quit)
button_quit.pack()
root.mainloop()
完整的错误
Traceback (most recent call last):
File "main.py", line 4, in <module>
my_img = ImageTk.PhotoImage(Image.open("test.png"))
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/PIL/ImageTk.py", line 112, in __init__
self.__photo = tkinter.PhotoImage(**kw)
File "/usr/lib/python3.8/tkinter/__init__.py", line 4064, in __init__
Image.__init__(self, 'photo', name, cnf, master, **kw)
File "/usr/lib/python3.8/tkinter/__init__.py", line 3997, in __init__
raise RuntimeError('Too early to create image')
RuntimeError: Too early to create image
Exception ignored in: <function PhotoImage.__del__ at 0x7f7148fadc10>
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/PIL/ImageTk.py", line 118, in __del__
name = self.__photo.name
AttributeError: 'PhotoImage' object has no attribute '_PhotoImage__photo'
解决方案
尝试这样做,可能是因为您在打开图像并创建照片对象后创建了根对象。
import os
from tkinter import *
from PIL import ImageTk,Image
root= Tk()
i = Image.open("C:/path/to/the/image/directory/image.png")
photo = ImageTk.PhotoImage(i)
root.mainloop()
推荐阅读
- c# - 在动态创建的手风琴窗格内使用动态创建的按钮的点击事件
- webpack - 无法解析“puppeteer-core/lib”中的“ws”
- ios - 根据上一个按下的按钮在下一个视图控制器中显示其他数组
- javascript - setAttribute 的工作原理
- excel - 改进计算时间以显示来自研究的几个不同结果
- python-3.x - Dataframe 通过查找另一个 Dataframe 中另一个 Dataframe 的出现来填充列值
- mongodb - 嵌套对象内的 MongoDB 查询
- html - Angular Accordion 可访问性问题
- c# - 无法访问已处置的对象。对象名称:'tlsxyz'
- java - Google Cloud Search 数据库连接器问题