子类化Tk时,Python PIL PhotoImage图像“ pyimage1”不存在

时间:2020-08-08 01:59:30

标签: python tkinter python-imaging-library

我正在尝试以编程方式扫描目录并显示该目录中的所有图像。但是,每次尝试将图像添加到Button小部件时,我都会不断遇到image "pyimage1" doesn't exist错误。我试图将对象引用分配给Button,但是它不能解决问题。我在做什么错了?

代码:

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)

1 个答案:

答案 0 :(得分:0)

由于您是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)