[Tutor] Help understanding classes

Danny Yoo dyoo at hashcollision.org
Sat Nov 15 02:33:01 CET 2014


On Fri, Nov 14, 2014 at 4:29 PM, Bo <crushed26 at gmail.com> wrote:
> Hello everyone, hope all is well. Was just wondering if I could get some
> help understanding classes and how they work. What is the point in OOP if I
> don’t understand classes, are classes not the heart and soul of OOP? I have
> been trying to learn classes by practicing with Tkinter building GUIs. Below
> is my code, which does work. It simply opens a window. I just don’t
> understand why it works?

GUI programming is a special class of programming.

What makes it significantly different from what you might be used to
is this: you eventually pass control of your program to some
third-party manager.  From that point forward, you don't do anything
on your own.  The third-party manager calls your functions when it
decides that something interesting has happened that needs your input.

This takes a large mental re-adjustment, from being the head, the one
in charge of control flow, to being a servant, a provider of a
service!

Note that I haven't said anything about OOP, because fundamentally I
think GUIs are different not because they're composed of classes, but
because control flow is driven by something else.


For Tkinter, the third-party manager is an "event loop" which we treat
as a black box.  We enter this event loop right here in your main
function:

#####################
 def main():
     root = Tk()
     # ... code cut
     root.mainloop()
######################

Once we reach root.mainloop(), it's the event loop that dictates what
happens next.  We take our hands off the steering wheel.


To follow along these lines, let's take a look at a simple button example here:

    http://effbot.org/tkinterbook/button.htm

Here's the code:

#############################################
import Tkinter
master = Tkinter.Tk()
def callback():
    print "click!"
b = Tkinter.Button(master, text="OK", command=callback)
b.pack()
Tkinter.mainloop()
#############################################

Here, we tell the GUI system: when you press this button, call our
"callback" function.  We run the mainloop().  A window appears with a
button, and when we press the button, we see that our function gets
called.


This is strange for beginners, because we're telling the GUI system
how to use our functions.  But we're not the ones calling them.  Also,
somehow we're using functions "in the future", rather than immediately
by calling them.

That's the big point of a line like:

    b = Tkinter.Button(master, text="OK", command=callback)

where "callback" is a function.  Note the lack of parens there!  It's
not being called yet.  Instead, the function is just a value that the
button knows about.  The event loop will call that function later on.

That's why we're saying "callback" instead of "callback()" on that line.


More information about the Tutor mailing list