Search code examples
pythonclassobjecttkinterself

What is the difference between self and not self objects particularly in Tkinter class?


I have this simple code with self.btn1

from tkinter import Tk, ttk, messagebox
import tkinter as tk

class Main(tk.Frame):
    def __init__(self, root):
        super().__init__(root)
        self.btn1 = ttk.Button(self, text="test")
        self.btn1.pack()

if __name__ == "__main__":
    root = tk.Tk()
    app = Main(root)
    app.pack()
    root.mainloop()

and this code without self button

from tkinter import Tk, ttk, messagebox
import tkinter as tk

class Main(tk.Frame):
    def __init__(self, root):
        super().__init__(root)
        btn1 = ttk.Button(self, text="test")
        btn1.pack()

if __name__ == "__main__":
    root = tk.Tk()
    app = Main(root)
    app.pack()
    root.mainloop()

Both of them work similarly, but what's the difference, which one should I use?


Solution

  • The only real difference lies in how easy it is to retrieve the reference to the Button instance should you need one. With the former, it's just app.btn1. With the latter, it's app.winfo_children()[0].

    >>> app.winfo_children()[0] is app.btn1
    True