Status Bars

Finally, most applications sport a status bar at the bottom of each application window. Implementing a status bar with Tkinter is trivial: you can simply use a suitably configured Label widget, and reconfigure the text option now and then. Here's one way to do it:

    status = Label(master, text="", bd=1, relief=SUNKEN, anchor=W)
    status.pack(side=BOTTOM, fill=X)

If you wish to be fancy, you can use the following class instead. It wraps a label widget in a convenience class, and provides set and clear methods to modify the contents.

Example 8-3. A Status Bar Class

# File: tkSimpleStatusBar.py

class StatusBar(Frame):

    def __init__(self, master):
        Frame.__init__(self, master)
        self.label = Label(self, bd=1, relief=SUNKEN, anchor=W)
        self.label.pack(fill=X)

    def set(self, format, *args):
        self.label.config(text=format % args)
        self.label.update_idletasks()

    def clear(self):
        self.label.config(text="")
        self.label.update_idletasks()

The set method works like C's printf function; it takes a format string, possibly followed by a set of arguments (a drawback is that if you wish to print an arbitrary string, you must do that as set("%s", string)). Also note that this method calls the update_idletasks method, to make sure pending draw operations (like the status bar update) are carried out immediately.

But the real trick here is that we've inherited from the Frame widget. At the cost of a somewhat awkward call to the frame widget's constructor, we've created a new kind of custom widget that can be treated as any other widget. You can create and display the status bar using the usual widget syntax:

    status = StatusBar(root)
    status.pack(side=BOTTOM, fill=X)

We could have inherited from the Label widget itself, and just extended it with set and clear methods. This approach have a few drawbacks, though: