tkinter help: difference between "master" and "root" keywords in this code?

Viewed 1163

I'm learning Tkinter and trying to understand OOP concepts. I came across this code online:

class MyFirstGUI:
    def __init__(self, master):
        self.master = master
        master.title("A simple GUI")

        self.label = Label(master, text="This is our first GUI!")
        self.label.pack()

        self.greet_button = Button(master, text="Greet", command=self.greet)
        self.greet_button.pack()

        self.close_button = Button(master, text="Close", command=master.quit)
        self.close_button.pack()

    def greet(self):
        print("Greetings!")

root = Tk()
my_gui = MyFirstGUI(root)
root.mainloop() 

This code worked perfectly, and I understand the widget features and what they do, however, I edited the code slightly as follows:

class Timer:

    def __init__(self, master):
        self.master = master
        master.title = ("A simple GUI")

        self.label = Label(master, text="first GUI")
        self.label.pack()

        self.greet_button = Button(master, text="Greet", command=self.greet)
        self.greet_button.pack()

        self.close_button = Button(master, text="Close", command=master.quit)
        self.close_button.pack()

    def greet(self):
        print("Greetings!")

master = Tk()
my_gui = Timer(master)
master.mainloop()

To my surprise, this code also worked perfectly. My question is, what is the difference using 'master' rather than 'root'? what is the 'master' keywords purpose in the code? From what I understand, 'self' is similar to the 'this' keyword in Java, so I'm assuming self and master aren't the same?

Thanks in advance for your help guys! Apologies if what I'm asking wasn't clear enough.

2 Answers

master and root are not keywords, they are metasyntactic variables, and don't mean anything special to the compiler. This code works perfectly fine as well:

class MyFirstGUI:
    def __init__(self, chickens):
        self.chickens = chickens
        chickens.title("A simple GUI")

        self.label = Label(chickens, text="This is our first GUI!")
        self.label.pack()

        self.greet_button = Button(chickens, text="Greet", command=self.greet)
        self.greet_button.pack()

        self.close_button = Button(chickens, text="Close", command=chickens.quit)
        self.close_button.pack()

    def greet(self):
        print("Greetings!")

stackoverflow = Tk()
my_gui = MyFirstGUI(stackoverflow)
stackoverflow.mainloop() 

Hope this helps!

I don't think there is any difference between whether you call it "master" or "root". People call it "root" because Tkinter widgets are placed in a tree so part of that would be a "root". People would call it "master" because all widgets have a parents they go to or also a master. So you could call it anything. I hope this answers helps

Related