I’m reading the Python GTK Tutorial. They have a lot of examples where they use derived classes of Gtk.Window to create windows containing various widgets. What I don’t understand is the use of instance variables in those examples. Please have a look at this “Hello World” program:
import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk
class MyWindow(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self, title="Hello World")
self.button = Gtk.Button(label="Click Here")
self.button.connect("clicked", self.on_button_clicked)
self.add(self.button)
def on_button_clicked(self, widget):
print("Hello World")
win = MyWindow()
win.connect("destroy", Gtk.main_quit)
win.show_all()
Gtk.main()
Why would I define button in this example as an instance variable? Why not use a local variable? The alternative I’m thinking of is:
button = Gtk.Button(label="Click Here")
button.connect("clicked", self.on_button_clicked)
self.add(button)
In other examples (like this one) they use local variables in a similar context… The only reason for defining instance variables I can think of is that I need access to those variables.