Leak in updating label

喜你入骨 提交于 2019-12-11 02:32:38

问题


I'm new to tkinter and have traced a memory leak in a project I'm doing down to a clock in my code. It turns out the memory leak happens when updating a label, the simplest example I've got it down to in code is:

import Tkinter as tk

class Display:
    def __init__(self, master):
        self.master = master
        self.tick()

    def tick(self):
        self.label = tk.Label(self.master, text = 'a')
        self.label.place(x=0,y=0)
        self.master.after(50, self.tick)

root = tk.Tk()
disp = Display(root)

If somebody could tell me why this leaks memory I'd be grateful.

Thanks, Matt


回答1:


The problem appears to be that you are creating Labels without destroying them. Each time you create a new label and place it over the old one, so it is still being referenced and thus can't be garbage collected.

Here is a slightly revised version that doesn't leak....

import Tkinter as tk

class Display:
    def __init__(self, master):
        self.label = None
        self.master = master
        self.tick()

    def tick(self):
        if self.label:
            self.label.destroy()
        self.label = tk.Label(self.master, text = 'a')
        self.label.place(x=0,y=0)
        self.master.after(50, self.tick)

root = tk.Tk()
disp = Display(root)



回答2:


The problem is that tick keeps creating new labels. There's no reason to create more than one label in a loop like this unless you really do need an ever increasing number of labels. You can update the text of a label widget by using the configure method.

For example:

def tick(self):
    self.label.configure(text=`my new text`)
    self.after(50, self.tick)


来源:https://stackoverflow.com/questions/8468198/leak-in-updating-label

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!