我只是想在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()

Label小部件只有在声明root = Tk()(Tk()启动底层Tcl解释器(后才能工作。然后,所有子窗口小部件都必须具有根作为它们的第一个参数(例如,Label(root, text='hi')(。您在尝试使用解释器后启动了它,因此Python引发了一个异常。

最新更新