Young
Young

Reputation: 757

what if there is no Tk() declaration in the code

So I came across a Python3 tkinter GUI code snippet and it doesn't have anything like root = Tk() but IT RUNS! I read this and it is really helpful. But my question is, if the tk window and interpreter is initiated when I create my first widget, how can I add more widgets to the root without specifying it? aka. What should I do when I want to add more widgets to the same program / same window, since I don't have a variable like root to store the root window object?

By the way, there was a controller class like this:

class Controller(tk.Tk):
    def __init__ (self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        parentObj = tk.Frame(self)
        self.allFrames = {}
        ...

Does it mean that the parentObj frame is the windows / outmost layer of frame in this app? How do I understand this class definition here? What is tk.Tk.__init__(self, *args, **kwargs) here for?

Upvotes: 0

Views: 93

Answers (1)

Bryan Oakley
Bryan Oakley

Reputation: 385970

Controller is a subclass of tk.Tk. Controller is identical to tk.Tk but with enhancements. Thus, doing something=Controller(...) serves the same purpose as something=tk.Tk().

What should I do when I want to add more widgets to the same program / same window,

Use self as the parent if inside the class, use the instance of the class if outside.

class Controller(tk.Tk):
    def __init__ (self, *args, **kwargs):
        ...
        self.some_widget = tk.Label(self, ...)

... and ...

root = Controller()
some_other_widget = tk.Label(root, ...)

Does it mean that the parentObj frame is the windows / outmost layer of frame in this app?

No. The outmost "layer" is the instance of Controller. That is the root window. parentObj lives inside that window.

What is tk.Tk.__init__(self, *args, **kwargs) here for?

This is just the standard python way for a subclass to initialize its parent class.

Upvotes: 1

Related Questions