Details

This sample application is written as a class. The constructor (the __init__ method) is called with a parent widget (the master), to which it adds a number of child widgets. The constructor starts by creating a Frame widget. A frame is a simple container, and is in this case only used to hold the other two widgets.

    class App:
        def __init__(self, master):

            frame = Frame(master)
            frame.pack()

The frame instance is stored in a local variable called frame. After creating the widget, we immediately call the pack method to make the frame visible.

We then create two Button widgets, as children to the frame.

    self.button = Button(frame, text="QUIT", fg="red", command=frame.quit)
    self.button.pack(side=LEFT)

    self.hi_there = Button(frame, text="Hello", command=self.say_hi)
    self.hi_there.pack(side=LEFT)

This time, we pass a number of options to the constructor, as keyword arguments. The first button is labelled "QUIT", and is made red (fg is short for foreground). The second is labelled "Hello". Both buttons also take a command option. This option specifies a function, or (as in this case) a bound method, which will be called when the button is clicked.

The button instances are stored in instance attributes. They are both packed, but this time with the side=LEFT argument. This means that they will be placed as far left as possible in the frame; the first button is placed at the frame's left edge, and the second is placed just to the right of the first one (at the left edge of the remaining space in the frame, that is). By default, widgets are packed relative to their parent (which is master for the frame widget, and the frame itself for the buttons). If the side is not given, it defaults to TOP.

The "hello" button callback is given next. It simply prints a message to the console everytime the button is pressed:

    def say_hi(self):
        print "hi there, everyone!"

Finally, we provide some script level code that creates a Tk root widget, and one instance of the App class using the root widget as its parent:

    root = Tk()

    app = App(root)

    root.mainloop()

The last call is to the mainloop method on the root widget. It enters the Tk event loop, in which the application will stay until the quit method is called (just click the QUIT button), or the window is closed.