清除用于Tkinter TEXT小部件

时间:2017-12-27 08:15:01

标签: python python-3.x tkinter textbox

在我的GUI中,我创建了一个ttk.notebook,然后将Text小部件放入每个选项卡中,并将日志/信息转储到这些Text小部件中。如果使用一组新的日志文件重新启动该进程,请.forget()旧选项卡,然后创建新的选项卡。我注意到,当我这样做时,原始Text小部件中使用的ram不会被清除。我怎样才能释放这只公羊?

示例:

from tkinter import *
from tkinter.ttk import Notebook
main = Tk()
def maker():
    nb = Notebook(main, name='nbook')
    nb.grid(row=0, column=0, columnspan=2)
    frame1 = Frame(name='frame1')
    txt = Text(frame1, wrap=NONE)
    txt.grid()
    nb.add(frame1, text='textwindow')
    txt.insert('end', 'hello\n' * 1000000)

def remover():
    print(main.winfo_children())
    for tab in main.children['nbook'].tabs():
        main.children['nbook'].forget(tab)
    print(main.winfo_children())

b1 = Button(main, text='Insert', command=maker)
b1.grid(row=1, column=0)
b2 = Button(main, text='Clear tabs', command=remover)
b2.grid(row=1, column=1)
main.mainloop()

在该示例中,当您单击“插入”时,它会创建窗口小部件并将一堆文本转储到其中。如果您使用“清除标签”按钮调用卸妆,则会忘记所有标签,但该文本使用的内存永远不会免费。即使您销毁文本小部件,ram也不会被释放。我怎样才能解决这个问题?

3 个答案:

答案 0 :(得分:2)

Text.delete('1.0', END)
Text.edit_reset()

将清除Text小部件的历史记录,因此在删除后调用此方法。 希望这能解决您的问题

答案 1 :(得分:1)

当您只需要配置其中一个属性时,销毁整个(一组)小部件听起来像一个非常糟糕的设计,并且这种做法因导致昂贵的内存泄漏而臭名昭着,正如您已经看到的那样。

无论如何,我认为只需配置你已经拥有的小部件就可以好得多,而不是在更改到期时销毁/重新创建小部件。

根据我能够理解的内容,您说您需要经常在Text窗口小部件中显示一些文本(即日志?),那么为什么不清除已有的文本和将新的插入到窗口小部件中:

txt.delete('1.0', 'end') # clearing the text widget
txt.insert('end', my_log) # inserting the log into the text widget

答案 2 :(得分:0)

我后来发现只是在选项卡上执行.forget()并没有消除小部件使用的内存。这可能是因为它们在其他地方被引用但我找不到源。如果我在选项卡本身上执行.destroy()之前从选项卡.forget()获取了小部件,那么内存最终将被垃圾收集器释放。对于我的情况,通过该工具运行一组新的日志会重用当前使用的内存,并且在它稍微停留之后释放额外的(如果有的话)。