Local variables to a function doesn't disapear after function execution. Why ?

ast nomail at com.invalid
Wed Oct 12 07:18:16 EDT 2016


Hello, here is the small program:

from tkinter import *

class Test:
    def __init__(self):
        root = Tk()
        label = Label(root, text="this is a test")
        label.pack()
        root.mainloop()

test=Test()

I dont understand why this program works. After execution
of function __init__, local variables 'root' and 'label' should 
disapear and the widgets Tk and Label should be garbage 
collected. But it's not the case, the window Tk is still on the 
screen with the label inside it. Why ?

Usually, we write:

class Test:
    def __init__(self):
        self.root = Tk()
        self.label = Label(self.root, text="this is a test")
        self.label.pack()
        self.root.mainloop()

test = Test()

to keep some references to Tk() and Label()



More information about the Python-list mailing list