0Nicholas
0Nicholas

Reputation: 419

How does Tkinter keep track of its widgets when used with classes?

from tkinter import *


class SampleClass:

    def __init__(self, master):  
        frame = Frame(master)
        frame.pack()
        self.printButton = Button(master, text = "PrintButton", command=self.printMessage)
        self.printButton.pack(side = LEFT)

    def printMessage(self):
        print("Hulk Smash!")

root = Tk()
samp = SampleClass(root)

root.mainloop()

The Tkinter root is passed to the class as a reference only once. So, when the root changes (pressing a button, or entering some text using entry widgets), the state of root is changed. How does the class samp know that the root has changed? I understand that the root.mainloop() method makes calls to the root in a loop but the class samp seems to have no idea of the changing reference. What am I missing here?

Upvotes: 0

Views: 159

Answers (1)

Bryan Oakley
Bryan Oakley

Reputation: 386285

Tkinter is a thin wrapper around a Tcl interpreter which has loaded the "tk" package. When you create a widget (eg: Frame(master)), this creates an object in the Tcl interpreter. It is the Tcl interpreter that keeps hold of the reference to the master widget, and it is the Tcl interpreter that responds to changes.

Upvotes: 1

Related Questions