Read Programming Python Online

Authors: Mark Lutz

Tags: #COMPUTERS / Programming Languages / Python

Programming Python (48 page)

BOOK: Programming Python
12Mb size Format: txt, pdf, ePub
ads

See the websites of these toolkits for more details. There are other
lesser-known GUI toolkits for Python, and new ones are likely to emerge by
the time you read this book (in fact, IronPython was new in the third
edition, and RIAs are new in the fourth). Moreover, packages like those in
this list are prone to mutate over time. For an up-to-date list of
available tools, search the Web or browse
http://www.python.org
and the PyPI third-party packages
index
maintained there.

[
24
]
In this book, “Windows” refers to the Microsoft Windows
interface common on PCs, and “X Windows” refers to the X11 interface
most commonly found on Unix and Linux platforms. These two interfaces
are generally tied to the Microsoft and Unix (and Unix-like)
platforms, respectively. It’s possible to run X Windows on top of a
Microsoft operating system and Windows emulators on Unix and Linux,
but it’s not common. As if to muddy the waters further, Mac OS X
supports Python’s tkinter on both X Windows and the native Aqua GUI
system directly, in addition to platform-specific cocoa options
(though it’s usually not too misleading to lump OS X in with the
“Unix-like” crowd).

tkinter Overview

Of all the prior section’s GUI options, though, tkinter is by far
the de facto standard way to implement portable user interfaces in Python
today, and the focus of this part of the book. The rationale for this
approach was explained in
Chapter 1
; in short, we
elected to present one toolkit in satisfying depth instead of many
toolkits in less-than-useful fashion. Moreover, most of the tkinter
programming concepts you learn here will translate directly to any other
GUI toolkit you choose to utilize.

tkinter Pragmatics

Perhaps more to
the point, though, there are pragmatic reasons that the
Python world still gravitates to tkinter as its de facto standard
portable GUI toolkit. Among them, tkinter’s accessibility, portability,
availability, documentation, and extensions have made it the most widely
used Python GUI solution for many years running:

Accessibility

tkinter is generally regarded as a
lightweight
toolkit
and one of the simplest GUI solutions for
Python available today. Unlike larger frameworks, it is easy to
get started in tkinter right away, without first having to grasp a
much larger class interaction model. As we’ll see, programmers can
create simple tkinter GUIs in a few lines of Python code and scale
up to writing industrial-strength GUIs gradually. Although the
tkinter API is basic, additional widgets can be coded in Python or
obtained in extension packages such as Pmw, Tix, and ttk.

Portability

A Python script that builds a GUI with tkinter will run
without source code changes on all major windowing platforms
today: Microsoft Windows, X Windows (on Unix and Linux), and the
Macintosh OS X (and also ran on Mac classics). Further, that same
script will provide a native look-and-feel to its users on each of
these platforms. In fact, this feature became more apparent as Tk
matured. A Python/tkinter script today looks like a Windows
program on Windows; on Unix and Linux, it provides the same
interaction but sports an appearance familiar to X Windows users;
and on the Mac, it looks like a Mac program should.

Availability

tkinter is a standard module in the Python library, shipped
with the interpreter. If you have Python, you have tkinter.
Moreover, most Python installation packages (including the
standard Python self-installer for Windows, that provided on Mac
OS X, and many Linux distributions) come with tkinter support
bundled. Because of that, scripts written to use the tkinter
module work immediately on most Python interpreters, without any
extra installation steps. tkinter is also generally better
supported than its alternatives today. Because the underlying Tk
library is also used by the Tcl and Perl programming languages
(and others), it tends to receive more development resources than
other toolkits available.

Naturally, other factors such as documentation and extensions are
important when using a GUI toolkit, too; let’s take a quick look at the
story tkinter has to tell on these fronts as well.

tkinter Documentation

This book explores
tkinter fundamentals and most widgets tools, and it should
be enough to get started with substantial GUI development in Python. On
the other hand, it is not an exhaustive reference to the tkinter library
or extensions to it. Happily, at least one book dedicated to using
tkinter in Python is now commercially available as I write this
paragraph, and others are on the way (search the Web for details).
Besides books, you can also find tkinter documentation online; a
complete set of tkinter manuals is currently maintained on the Web at
http://www.pythonware.com/library
.

In addition, because the underlying Tk toolkit used by tkinter is
also a de facto standard in the open source scripting community at
large, other documentation sources apply. For instance, because Tk has
also been adopted by the Tcl and Perl programming languages, Tk-oriented
books and documentation written for both of these are directly
applicable to Python/tkinter as well (albeit, with some syntactic
mapping).

Frankly, I learned tkinter by studying Tcl/Tk texts and
references—just replace Tcl strings with Python objects and you have
additional reference libraries at your disposal (see
Table 7-2
, the Tk-to-tkinter conversion guide,
at the end of this chapter for help reading Tk documentation). For
instance, the book
Tcl/Tk Pocket
Reference
(O’Reilly) can serve as a nice supplement
to the tkinter tutorial material in this part of the book. Moreover,
since Tk concepts are familiar to a large body of programmers, Tk
support is also readily available on the Net.

After you’ve learned the basics, examples can help, too. You can
find tkinter demo programs, besides those you’ll study in this book, at
various locations around the Web. Python itself includes a set of demo
programs in the
Demos\tkinter
subdirectory of its source distribution package. The IDLE development
GUI mentioned in the next section makes for an interesting code read as
well.

tkinter Extensions

Because tkinter is
so widely used, programmers also have access to precoded
Python extensions designed to work with or augment it. Some of these may
not yet be available for Python 3.X as I write this but are expected to
be soon. For instance:

Pmw

Python Mega Widgets
is an extension toolkit for building high-level
compound widgets in Python using the tkinter module. It extends
the tkinter API with a collection of more sophisticated widgets
for advanced GUI development and a framework for implementing some
of your own. Among the precoded and extensible megawidgets shipped
with the package are notebooks, combo boxes, selection widgets,
paned widgets, scrolled widgets, dialog windows, button boxes,
balloon help, and an interface to the Blt graph widget.

The interface to Pmw megawidgets is similar to that of basic
tkinter widgets, so Python scripts can freely mix Pmw megawidgets
with standard tkinter widgets. Moreover, Pmw is pure Python code,
and so requires no C compiler or tools to install. To view its
widgets and the corresponding code you use to construct them, run
the
demos\All.py
script in the Pmw
distribution package. You can find Pmw at
http://pmw.sourceforge.net
.

Tix

Tix is a
collection of more than 40 advanced widgets,
originally written for
Tcl/Tk
but now available for use in
Python/tkinter programs. This package is now a Python standard
library module, called
tkinter.tix
. Like Tk, the underlying Tix
library is also shipped today with Python on Windows. In other
words, on Windows, if you install Python, you also have Tix as a
preinstalled library of additional widgets.

Tix includes many of the same devices as Pmw, including spin
boxes, trees, tabbed notebooks, balloon help pop ups, paned
windows, and much more. See the Python library manual’s entry for
the Tix module for more details. For a quick look at its widgets,
as well as the Python source code used to program them, run the
tixwidgets.py
demonstration program in the
Demo\tix
directory of the Python source distribution (this directory is not
installed by default on Windows and is prone to change—you can
generally find it after fetching and unpacking Python’s source
code from Python.org).

ttk

Tk themed widgets,
ttk, is a relatively new widget set which attempts
to separate the code implementing a widget’s behavior from that
implementing its appearance. Widget classes handle state and
callback invocation, whereas widget appearance is managed
separately by themes. Much like Tix, this extension began life
separately, but was very recently incorporated into Python’s
standard library in Python 3.1, as module
tkinter.ttk
.

Also like Tix, this extension comes with advanced widget
types, some of which are not present in standard tkinter itself.
Specifically, ttk comes with 17 widgets, 11 of which are already
present in tkinter and are meant as replacements for some of
tkinter’s standard widgets, and 6 of which are new—Combobox,
Notebook, Progressbar, Separator, Sizegrip and Treeview. In a
nutshell, scripts import from the ttk module after tkinter in
order to use its replacement widgets and configure style objects
possibly shared by multiple widgets, instead of configuring
widgets
themselves
.

As we’ll see in this chapter, it’s possible to provide a
common look-and-feel for a set of widgets with standard tkinter,
by subclassing its widget classes using normal OOP techniques (see
Customizing Widgets with Classes
). However, ttk
offers additional style options and advanced widget types. For
more details on ttk widgets, see the entry in the Python library
manual or search the Web; this book focuses on tkinter
fundamentals, and tix and ttk are both too large to cover in a
useful fashion here.

PIL

The Python Imaging Library (PIL)
is an open source extension package that adds
image-processing tools to Python. Among other things, it provides
tools for image thumbnails, transforms, and conversions, and it
extends the basic tkinter image object to add support for
displaying many image file types. PIL, for instance, allows
tkinter GUIs to display JPEG, TIFF, and PNG images not supported
by the base tkinter toolkit itself (without extension, tkinter
supports GIFs and a handful of bitmap formats). See the end of
Chapter 8
for more details
and examples; we’ll use PIL in this book in a number of
image-related example scripts. PIL can be found at
http://www.pythonware.com
or via a web
search.

IDLE

The IDLE
integrated Python development environment is both
written in Python with tkinter and shipped and installed with the
Python package (if you have a recent Python interpreter, you
should have IDLE too; on Windows, click the Start button, select
the Programs menu, and click the Python entry to find it). IDLE
provides syntax-coloring text editors for Python code,
point-and-click debugging, and more, and is an example of
tkinter’s utility.

Others

Many of the extensions that provide visualization tools for
Python are based on the tkinter library and its canvas widget. See
the PyPI website and your favorite web search engine for more
tkinter extension examples.

If you plan to do any commercial-grade GUI development with
tkinter, you’ll probably want to explore extensions such as Pmw, PIL,
Tix, and ttk after learning tkinter basics in this text. They can save
development time and add pizzazz to your GUIs. See the Python-related
websites mentioned earlier for up-to-date details and
links.

tkinter Structure

From a more nuts-and-bolts perspective, tkinter is an integration
system that implies a somewhat unique program structure. We’ll see what
this means in terms of code in a moment, but here is a brief
introduction to some of the terms and concepts at the core of Python GUI
programming.

Implementation structure

Strictly speaking,
tkinter is simply the name of Python’s interface to
Tk
—a GUI library originally written for use with
the Tcl programming language and developed by Tcl’s creator, John
Ousterhout. Python’s tkinter module talks to Tk, and the Tk library in
turn interfaces with the underlying window system: Microsoft Windows,
X Windows on Unix, or whatever GUI system your Python uses on your
Macintosh. The portability of tkinter actually stems from the
underling Tk library it wraps.

Python’s tkinter adds a software layer on top of Tk that allows
Python scripts to call out to Tk to build and configure interfaces and
routes control back to Python scripts that handle user-generated
events (e.g., mouse clicks). That is, GUI calls are internally routed
from Python script, to tkinter, to Tk; GUI events are routed from Tk,
to tkinter, and back to a Python script. In
Chapter 20
, we’ll know these transfers
by their C integration terms,
extending
and
embedding
.

Technically, tkinter is today structured as a combination of the
Python-coded
tkinter
module
package’s files and an extension module called
_tkinter
that is written in C.
_tkinter
interfaces with the Tk library
using extending tools and dispatches callbacks back to Python objects
using embedding tools;
tkinter
simply adds a class-based interface on top of
_tkinter
. You should almost always import
tkinter
in your scripts, though,
not
_tkinter
; the latter is an
implementation module meant for internal use only (and was oddly named
for that reason).

Programming structure

Luckily, Python
programmers don’t normally need to care about all this
integration and call routing going on internally; they simply make
widgets and register Python functions to handle widget events. Because
of the overall structure, though, event handlers are usually known
as
callback
handlers, because the GUI
library “calls back” to Python code when events occur.

In fact, we’ll find that Python/tkinter programs are entirely
event driven
: they build displays and register
handlers for events, and then do nothing but wait for events to occur.
During the wait, the Tk GUI library runs an event loop that watches
for mouse clicks, keyboard presses, and so on. All application program
processing happens in the registered callback handlers in response to
events. Further, any information needed across events must be stored
in long-lived references such as global variables and class instance
attributes. The notion of a traditional linear program control flow
doesn’t really apply in the GUI domain; you need to think in terms of
smaller chunks.

In Python, Tk also becomes
object oriented
simply because Python is object oriented: the tkinter layer exports
Tk’s API as Python classes. With tkinter, we can either use a simple
function-call approach to create widgets and interfaces, or apply
object-oriented techniques such as inheritance and composition to
customize and extend the base set of tkinter classes. Larger tkinter
GUIs are generally constructed as trees of linked tkinter widget
objects and are often implemented as Python classes to provide
structure and retain state information between events. As we’ll see in
this part of the book, a tkinter GUI coded with classes almost by
default becomes a reusable software component.

BOOK: Programming Python
12Mb size Format: txt, pdf, ePub
ads

Other books

An Act of Love by Brooke Hastings
Secondary Targets by Sandra Edwards
The Cabin by Carla Neggers
Terror in D.C. by Randy Wayne White
Blood Tears by Michael J. Malone
Contrary Pleasure by John D. MacDonald
420 by Kenya Wright, Jackie Sheats
His Bodyguard by Greiman, Lois
I Have Iraq in My Shoe by Gretchen Berg