对于tkinter标签图像,为什么带有PhotoImage对象的本地名称不起作用? [英] Why doesn't a local name with a PhotoImage object work, for a tkinter label image?

查看:100
本文介绍了对于tkinter标签图像,为什么带有PhotoImage对象的本地名称不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个从tkinter库继承Tk的python类. 我想在其中添加带有图像的标签,但是仅当我将Photoimage创建为"self"的变量时,该标签才有效.

I have created a python class which inherits Tk from tkinter library. I want to add a label with an image to it but it only works when I create a Photoimage as variable to 'self'.

此代码有效:

class HMIDrawer(Tk):

    def __init__(self):
        super().__init__()

        self.frame = Frame(self)
        self.img = PhotoImage(file='resources/platoontomtom_empty.png')
        self.label = Label(self.frame, image=self.img, bg='white')
        self.label.pack()
        self.frame.pack()
        self.mainloop()

此代码不起作用:

class HMIDrawer(Tk):

    def __init__(self):
        super().__init__()

        self.frame = Frame(self)
        img = PhotoImage(file='resources/platoontomtom_empty.png')
        self.label = Label(self.frame, image=img, bg='white')
        self.label.pack()
        self.frame.pack()
        self.mainloop()

谁能解释为什么第一个代码起作用而第二个代码不能起作用?

Can anyone explain why the first code does work and the second code doesn't?

推荐答案

PhotoImage从文件中读取图像数据,并将其作为像素缓冲区存储在内存中.只要应用程序运行(或至少只要显示图像的Label小部件存在),该缓冲区的引用就必须是持久的.

PhotoImage reads the image data from file and stores it in memory as a pixel buffer. The reference of this buffer has to be persistent as long as the application runs (or at least, as long the Label widget showing the image exists).

如果将PhotoImage的结果放入局部变量(例如第二个代码中的img),则垃圾收集器可能会破坏此局部变量引用的数据.另一方面,如果将像素缓冲区的引用存储在属性中(例如,如第一个代码中的self.img),则只要self存在,垃圾收集器就不会破坏您的数据,这意味着只要该应用程序正在运行...

If you put the result of PhotoImage in a local variable (e.g. img, as in the second code), the garbage collector is likely to destroy the data referenced by this local variable. On the other hand, if you store the reference of your pixel buffer in an attribute (e.g. self.img, as in the first code) the garbage collector will not destroy your data as long as self exists, which means as long as the application runs...

如果您的GUI使用许多图像,通常的做法是创建一个属性self.images,该属性将所有需要的图像放入元组或字典中(无论您是希望按数字还是按字符串对它们进行索引),以确保图像将保存在内存中.

If your GUI uses many images, a usual practice is to create an attribute self.images that puts all required images either in a tuple or a dictionary (whether you prefer indexing them by numbers or by strings), that ensures that all images will be kept in memory.

这篇关于对于tkinter标签图像,为什么带有PhotoImage对象的本地名称不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆