首页 > 解决方案 > python problem regarding of creation of objects using loop

问题描述

I am new to python and while I was studying a book named python GUI cookbook, I ran into a piece of code I do not fully understand:

enter image description here

In Line 95 to 98 the author creates a loop for making objects of radio button from Tkinter library.

In a previous lessons I learned about garbage collection. I would therefore expect in the next iteration of the loop, when the radio button is replaced, that the previous button would be reclaimed by garbage collection.

How do all three of them keep existing if they are reclaimed by garbage collection?

标签: pythontkinter

解决方案


这确实是一个关于 Tkinter 实现的问题。

GC 将在下一次迭代中收集对象是正确的,除非其他东西也在引用该对象。在没有阅读 Tkinter 代码库的情况下,我的假设是,当您传递win到时Radiobutton(),该对象会将自身添加到win,现在保留对您的对象的引用。

此附加引用可防止 GC 收集您的对象。

开源的美妙之处在于您可以自己寻找:

https://github.com/python/cpython/blob/e42b705188271da108de42b55d9344642170aa2b/Lib/tkinter/init .py# L2285

最后一件事BaseWidget__init__以下(self.master是你的win论点):

self.master.children[self._name] = self

这将类似于:

foo = []

for x in range(3):
    tmp = dict(bar=x)
    foo.append(tmp)

tmp被重新分配,但基础对象的引用已添加到foo.


推荐阅读