Image 使用Tkinter中的图像作为图标以获得最佳性能的方法

Image 使用Tkinter中的图像作为图标以获得最佳性能的方法,image,python-3.x,user-interface,tkinter,icons,Image,Python 3.x,User Interface,Tkinter,Icons,目前我正在创建tkinter GUI应用程序,我正在使用一些图像作为treeview小部件中项目的图标。为了阅读并将其作为参考,我使用了以下代码: self.logoadd = tk.PhotoImage(file='../img/add.png') self.logodel = tk.PhotoImage(file='../img/delete.png') ... self.logoedit = tk.PhotoImage(file='../img/edit.png') #Keep them

目前我正在创建tkinter GUI应用程序,我正在使用一些图像作为treeview小部件中项目的图标。为了阅读并将其作为参考,我使用了以下代码:

self.logoadd = tk.PhotoImage(file='../img/add.png')
self.logodel = tk.PhotoImage(file='../img/delete.png')
...
self.logoedit = tk.PhotoImage(file='../img/edit.png')

#Keep them as references
self.imgAdd = self.logoadd
self.imgDel = self.logodel
...
self.imgEdit = self.logoedit
我认为如果使用的图像超过30张,这不是一个好的做法。我想到的另一个方法是:

  • 将图像作为字节字符串存储在.py文件或中
  • 使用for循环检索文件夹中的所有图像并将其作为变量传递
我需要一些经验丰富的GUI开发人员的建议。为了提高GUI实践中的性能和使用率,哪种方法是最好的?(可能是我所有的方式都错了)


有关信息:这些图像的大小为16x16,用于文件图标的图像

我在涉及
PhotoImage
的多个tkinter应用程序中使用的是将图像加载到字典中,以保持对它们的引用

您可以像这样手动操作,如果您有一些设置的图像,建议这样做,因为这样更容易看到您拥有的内容

import tkinter as tk

image_cache = { 'add' : tk.PhotoImage(file = 'add.png'),
                ...
            }
或者更紧凑和动态的方法是使用
os
模块和字典理解。使用此方法,您的所有密钥都将成为图像的文件名,以便更轻松地访问所需的图像

import os
import tkinter as tk

filepath = '../img/'
image_cache = { os.path.splitext(filename)[0] : tk.PhotoImage(
    file = os.path.join(filepath, filename))
               for filename in os.listdir(filepath) }

>>> image_cache['add'] # gets the PhotoImage for 'add.png'

我不确定这种方法是否能提供最佳性能,但它干净、紧凑且可用。

我不太理解您所说的最佳性能是什么意思,因为您似乎在寻求一种避免写出30多个项目作业的方法。如果是这样的话,那么使用字典来保存所有的
PhotoImage
,并使用指定的键获取它。我的意思是,最好的性能是速度和代码。在treeview中,可能有上百个项目,它们的图标可能不同。因此,读取合适的图像并将其放入GUI应该是快速且易于维护的。除非您有数千或上万个图像,否则性能差异将是难以察觉的。非常感谢,@Steven Summers。2-variant适合我的情况,并且运行良好。