如何让图片永久显示在treeview中?

How to make images permanently display in treeview?

我找到了一个函数,该函数 returns 具有给定文件路径的位图图标。 除此之外,我还有一个功能,可以在给定目录中创建包含文件和文件夹的树。 我希望我的树显示目录名称及其图标,但它只显示名称。我采用了面向对象的编码方法。

    def populate(self, path):
        if os.path.isdir(path):
            with os.scandir(path) as it:
                for entry in it:
                    if not entry.name.startswith('.') and entry.is_dir():
                        values1 = [time.asctime(time.localtime(os.path.getmtime(entry.path))), "Folder",
                                   os.path.getsize(entry.path)]
                        self.tree.insert("", 'end', text=entry.name, values=values1, open=False, image=self.folderimg)
                    if not entry.name.startswith('.') and entry.is_file():
                        icon_id = iconHelper.get_icon(path=entry.path, size="small")
                        icon = ImageTk.PhotoImage(icon_id)
                        values2 = [time.asctime(time.localtime(os.path.getmtime(entry.path))), "File",
                                   os.path.getsize(entry.path)]
                        self.tree.insert("", 'end', text=entry.name, values=values2, open=False, image=icon)
        else:
            try:
                os.startfile(path)
            except OSError:
                print("File can not be opened")

“填充”功能在 class 中。我知道 icon 变量的范围是局部的。我尝试了 self.icon 方法,但它不起作用

我怎样才能使每个“图标”变量的范围成为 class 的全局变量?

您可以简单地使用类型 list 的实例变量来存储这些图标图像:

def populate(self, path):
    if os.path.isdir(path):
        self.icons = [] # instance variable to store those icon images
        with os.scandir(path) as it:
            for entry in it:
                if not entry.name.startswith('.') and entry.is_dir():
                    values1 = [time.asctime(time.localtime(os.path.getmtime(entry.path))), "Folder",
                               os.path.getsize(entry.path)]
                    self.tree.insert("", 'end', text=entry.name, values=values1, open=False, image=self.folderimg)
                if not entry.name.startswith('.') and entry.is_file():
                    icon_id = iconHelper.get_icon(path=entry.path, size="small")
                    icon = ImageTk.PhotoImage(icon_id)
                    values2 = [time.asctime(time.localtime(os.path.getmtime(entry.path))), "File",
                               os.path.getsize(entry.path)]
                    self.tree.insert("", 'end', text=entry.name, values=values2, open=False, image=icon)
                    self.icons.append(icon) # save the reference of the icon image
    else:
        try:
            os.startfile(path)
        except OSError:
            print("File can not be opened")