首页 > 解决方案 > 我只是想在 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'

标签: pythonpython-3.ximagetkinter

解决方案


尝试这样做,可能是因为您在打开图像并创建照片对象后创建了根对象。

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()

推荐阅读