Python3.7 Tkinter帧参考不断增加

Python3.7 Tkinter帧参考不断增加,python,python-3.x,tkinter,Python,Python 3.x,Tkinter,抱歉,我对这个很陌生 我似乎无法“覆盖”我的tkinter帧。我写这篇文章是为了证明我的问题: from tkinter import * bgCol = 'red' def destroyMasterFrame(): global master master.destroy() createMasterFrame() def createMasterFrame(): global master, bgCol if bgCol == 'green'

抱歉,我对这个很陌生

我似乎无法“覆盖”我的tkinter帧。我写这篇文章是为了证明我的问题:

from tkinter import *

bgCol = 'red'

def destroyMasterFrame():
    global master
    master.destroy()
    createMasterFrame()

def createMasterFrame():
    global master, bgCol

    if bgCol == 'green':
        bgCol = 'red'
    else:
        bgCol='green'

    master = Frame(root, bg=bgCol)
    master.bind("<Button-1>", lambda event: destroyMasterFrame())
    master.pack(side='top', fill='both', expand='yes')
    print(master)

root = Tk()
root.geometry('200x200+100+100')

createMasterFrame()

root.mainloop()
…每次我点击。我知道我可能错过了一些基本的东西,但任何帮助都将不胜感激。谢谢

编辑:

如果我将一个图像添加到我正在销毁的帧中,它似乎会将其与帧引用一起保存在内存中,而这似乎会通过重复使用快速填充内存。这段代码演示了我的意思。。。我如何销毁框架及其引用,并从内存中删除其中包含的所有内容

from tkinter import *

def destroyMasterFrame():
    global master
    master.destroy()
    createMasterFrame()

def createMasterFrame():
    global master

    master = Frame(root, bg='green')
    master.pack(side='top', fill='both', expand='yes')

    img = PhotoImage(file='test.png')
    label = Label(master, image=img)
    label.image = img
    label.bind("<Button-1>", lambda event: test())
    label.pack(side='top', fill='both', expand='yes')

    print(master)

def test():
    global myrange
    myrange = 1000
    for x in range(myrange):
        createMasterFrame()
        destroyMasterFrame()

root = Tk()
root.geometry('200x200+100+100')

createMasterFrame()

root.mainloop()
从tkinter导入*
def主框架():
全局主控
毁灭大师
createMasterFrame()
def createMasterFrame():
全局主控
主帧=帧(根,bg='green')
master.pack(侧边class='top',填充class='both',展开class='yes')
img=PhotoImage(file='test.png')
标签=标签(主图像=图像)
label.image=img
label.bind(“,lambda事件:test())
label.pack(side='top',fill='both',expand='yes')
打印(母版)
def test():
全球myrange
myrange=1000
对于范围内的x(myrange):
createMasterFrame()
主框架()
root=Tk()
根几何体('200x200+100+100')
createMasterFrame()
root.mainloop()

再次感谢你的帮助

您正在真正删除帧:

def destroyMasterFrame():
    master.destroy()
    print(master)
如果您检查框架是否已删除。
此堆栈的引用仍处于活动状态。
无论如何,删除的只是框架,而不是引用。
因此,即使帧不在后面,tkinter仍会向上计数。
所以不要担心,继续走这条路。
提示:您不需要两次使用全局

编辑:(根据您的评论)

应在不清除引用的情况下工作(不知道如何进行)。

应该有一个限制2^63谢谢你,这真的很有帮助。所以,如果我运行这个程序,有人点击了数千次,那还可以吗?或者我需要在某个时候清除引用吗?再次感谢您的回复。再次感谢费边的帮助。。。但是,我注意到,当我运行这个程序时,程序占用的内存会随着它的运行而增加。如果这是一个长时间运行的程序,那么如何阻止这种情况发生。此外,这只是一个简单的框架与背景颜色。。。如果我将图像添加到帧中并再次运行它,即使我破坏了帧,程序内存也会随着程序的运行而大量增加,就像它一次又一次地存储图像,而不是每次都破坏它一样。为了证明这一点,我用测试脚本编辑了原始问题。谢谢。@gee702您的测试用例的问题是您在“销毁”函数中“创建”了第二个主框架,但您只销毁了在循环中创建的主框架,因此每个循环将至少堆叠一个主框架^^-如果您更改此项,它将起作用:)
def destroyMasterFrame():
    master.destroy()
    print(master)
myrange = 100000
for x in range(myrange):
    createMasterFrame()
    destroyMasterFrame()
    if x == myrange-1:
        print(master)