Python PIL PhotoImage Image "pyimage1"在子类化 Tk 时不存在



我正在尝试以编程方式扫描一个目录并显示该目录中的所有图像。然而,每次我尝试向Button小部件添加图像时,都会不断出现image "pyimage1" doesn't exist错误。我试图为按钮分配一个对象引用,但它没有修复它。我做错了什么?

代码:

class App(tkinter.Tk):
def __init__(self, directory):
super().__init__()
self.directory = directory
self.frame = ttk.Frame(self)
for image in filter(lambda name: name.endswith(".jpg"), os.listdir("images")):
img = open(os.path.join(self.directory, image)).resize((320, 180))
image_obj = PhotoImage(img)
button = ttk.Button(self.frame, text=image, command=lambda: do_something(image))
button.image = image_obj
button.configure(image=image_obj)

由于您正在对Tk对象进行子类化,请尝试使该类成为Button对象的主类。

class App(tkinter.Tk):
def __init__(self):
super().__init__()
for image in filter(lambda name: name.endswith(".jpg"), os.listdir("PATH")):
img = open(os.path.join(self.directory, image)).resize((320, 180))
image_obj = PhotoImage(img, master=self)
button = ttk.Button(self.frame, text=image, command=lambda: None)
button.image = image_obj
button.configure(image=image_obj)

最新更新