更新标签时泄漏
我是 tkinter 的新手,并且在我正在做的项目中跟踪到了代码中的时钟的内存泄漏。事实证明,更新标签时会发生内存泄漏,我在代码中得到的最简单的例子是:
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)
如果有人能告诉我为什么会泄漏内存,我将不胜感激。
谢谢,马特
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题是
tick
不断创建新标签。没有理由在这样的循环中创建多个标签,除非您确实需要越来越多的标签。您可以使用configure
方法更新标签小部件的文本。例如:
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 theconfigure
method.For example:
问题似乎是您正在创建标签而不销毁它们。每次创建新标签并将其放置在旧标签之上时,它仍然被引用,因此无法被垃圾收集。
这是一个稍微修改过的版本,不会泄漏......
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....