Newbie question on instance variables

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)

    def on_button_clicked(self, widget):
        print("Hello World")

win = MyWindow()
win.connect("destroy", Gtk.main_quit)

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)

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.

You use instance members when you want the state of that application/object to live together. When you just have random local variables, you don’t know what goes together besides everything being tied to the module they’re defined in.