user12854400
user12854400

Reputation:

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?

Upvotes: 1

Views: 608

Answers (2)

Bryan Oakley
Bryan Oakley

Reputation: 386275

The difference is that btn1 is a local variable that is only available in the function in which it is used. self.btn1 is an instance variable that is available in every function within the class.

Upvotes: 0

chepner
chepner

Reputation: 532003

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

Upvotes: 1

Related Questions