问题
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