Read Programming Python Online

Authors: Mark Lutz

Tags: #COMPUTERS / Programming Languages / Python

Programming Python (46 page)

BOOK: Programming Python
5.45Mb size Format: txt, pdf, ePub
ads
Running the Script

Now, when
Example 6-23
is
run from the command line, if all goes well its canned self-test code at
the end opens a number of audio, image, text, and other file types
located in the script’s directory, using either platform-specific
players or a general web browser. On my Windows 7 laptop, GIF and HTML
files open in new IE browser tabs; JPEG files in Windows Photo Viewer;
plain text files in Notepad; DOC and XLS files in Microsoft Word and
Excel; and audio files in Windows Media Player.

Because the programs used and their behavior may vary widely from
machine to machine, though, you’re best off studying this script’s code
and running it on your own computer and with your own test files to see
what happens. As usual, you can also test it interactively (use the
package path like this one to import from a different directory,
assuming your module search path includes the PP4E root):

>>>
from PP4E.System.Media.playfile import playfile
>>>
playfile(r'C:\movies\mov10428.mpg')
# video/mpeg

We’ll use the
playfile
module
again as an imported library like this in
Chapter 13
to open media files downloaded by
FTP. Again, you may want to tweak this script’s tables for your players.
This script also assumes the media file is located on the local machine
(even though the
webbrowser
module
supports remote files with “http://” names), and it does not currently
allow different players for most different MIME subtypes (it
special-cases text to handle “plain” and “html” differently, but no
others). In fact, this script is really just something of a simple
framework that was designed to be extended. As always, hack on; this is
Python,
after all.

Automated Program Launchers (External)

Finally, some
optional reading—in the examples distribution package for
this book (available at sites listed in the
Preface
)
you can find additional system-related scripts we do not have space to
cover here:

  • PP4E\Launcher.py
    —contains
    tools used by some GUI programs later in the book to start Python
    programs without any environment configuration. Roughly, it sets up
    both the system path and module import search paths as needed to run
    book examples, which are inherited by spawned programs. By using this
    module to search for files and configure environments automatically,
    users can avoid (or at least postpone) having to learn the intricacies
    of manual environment configuration before running programs. Though
    there is not much new in this example from a system interfaces
    perspective, we’ll refer back to it later, when we explore GUI
    programs that use its tools, as well as those of its
    launchmodes
    cousin, which we wrote in
    Chapter 5
    .

  • PP4E\Launch_PyDemos.pyw
    and
    PP4E\Launch_PyGadgets_bar.pyw
    —use
    Launcher.py
    to start major GUI
    book examples without any environment configuration. Because all
    spawned processes inherit configurations performed by the launcher,
    they all run with proper search path settings. When run directly, the
    underlying
    PyDemos2.pyw
    and
    PyGadgets_bar.pyw
    scripts (which we’ll explore
    briefly at the end of
    Chapter 10
    )
    instead rely on the configuration settings on the underlying machine.
    In other words,
    Launcher
    effectively hides configuration details from the GUI interfaces by
    enclosing them in a configuration program layer.

  • PP4E\LaunchBrowser.pyw
    —portably locates and
    starts an Internet web browser program on the host machine in order to
    view a local file or remote web page. In prior versions, it used tools
    in
    Launcher.py
    to search for a
    reasonable browser to run. The original version of this example has
    now been largely superseded by the standard library’s
    webbrowser
    module, which arose after this
    example had been developed (reptilian minds think alike!). In this
    edition,
    LaunchBrowser
    simply
    parses command-line arguments for backward compatibility and invokes
    the
    open
    function in
    webbrowser
    . See this module’s help text, or
    PyGadgets and PyDemos in
    Chapter 10
    , for
    example command-line usage.

That’s the end of our system tools exploration. In the next part of
this book we leave the realm of the system shell and move on to explore
ways to add graphical user interfaces to our program. Later, we’ll do the
same using web-based approaches. As we continue, keep in mind that the
system tools we’ve studied in this part of the book see action in a wide
variety of programs. For instance, we’ll put threads to work to spawn
long-running tasks in the GUI part, use both threads and processes when
exploring server implementations in the Internet part, and use files and
file-related system calls throughout the remainder of the book.

Whether your interfaces are command lines, multiwindow GUIs, or
distributed client/server websites, Python’s system interfaces toolbox is
sure to play a important part in your Python programming future.

Part III. GUI Programming

This part of the book shows you how to apply Python to build
portable graphical user interfaces, primarily with Python’s standard
tkinter library. The following chapters cover this topic in depth:

Chapter 7

This chapter outlines GUI options available to Python
developers, and then presents a brief tutorial that illustrates core
tkinter coding concepts.

Chapter 8

This chapter begins a two-part tour of the tkinter library—its
widget set and related tools. This first tour chapter covers simpler
library tools and widgets: pop-up windows, various types of buttons,
images, and so on.

Chapter 9

This chapter continues the library tour begun in the prior
chapter. It presents the rest of the tkinter widget library,
including menus, text, canvases, scroll bars, grids, and time-based
events and animation.

Chapter 10

This chapter takes a look at GUI programming techniques: we’ll
learn how to build menus automatically from object templates, spawn
GUIs as separate programs, run long-running tasks in parallel with
threads and queues, and more.

Chapter 11

This chapter pulls the earlier chapters’ ideas together to
implement a collection of user interfaces. It presents a number of
larger GUIs—clocks, text editors, drawing programs, image viewers,
and so on—which also demonstrate general Python
programming-in-the-large concepts along the way.

As in the first part of this book, the material presented here is
applicable to a wide variety of domains and will be utilized again to
build domain-specific user interfaces in later chapters of this book. For
instance, the PyMailGUI and PyCalc examples of later chapters will assume
that you’ve covered the basics here.

Chapter 7. Graphical User Interfaces
“Here’s Looking at You, Kid”

For most software systems, a graphical user interface (GUI) has
become an expected part of the package. Even if the GUI acronym is new to
you, chances are that you are already familiar with such interfaces—the
windows, buttons, and menus that we use to interact with software
programs. In fact, most of what we do on computers today is done with some
sort of point-and-click graphical interface. From web browsers to system
tools, programs are routinely dressed up with a GUI component to make them
more flexible and easier to use.

In this part of the book, we will learn how to make Python scripts
sprout such graphical interfaces, too, by studying examples of programming
with the
tkinter
module, a portable GUI library that
is a standard part of the Python system and the toolkit most widely used
by Python programmers. As we’ll see, it’s easy to program user interfaces
in Python scripts thanks to both the simplicity of the language and the
power of its GUI libraries. As an added bonus, GUIs programmed in Python
with tkinter are automatically portable to all major computer
systems.

GUI Programming Topics

Because GUIs are
a major area, I want to say a few more words about this
part of the book before we get started. To make them easier to absorb,
GUI programming topics are split over the next five chapters:

  • This chapter begins with a quick tkinter tutorial to teach
    coding basics. Interfaces are kept simple here on purpose, so you
    can master the fundamentals before moving on to the following
    chapter’s interfaces. On the other hand, this chapter covers all the
    basics: event processing, the
    pack
    geometry manager, using inheritance
    and composition in GUIs, and more. As we’ll see, object-oriented
    programming (OOP) isn’t required for tkinter, but it makes GUIs
    structured and reusable.

  • Chapters
    8
    and
    9
    take you on a tour of the tkinter
    widget set.
    [
    23
    ]
    Roughly,
    Chapter 8
    presents simple widgets and
    Chapter 9
    covers more advanced
    widgets and related tools. Most of the interface devices you’re
    accustomed to seeing—sliders, menus, dialogs, images, and their
    kin—show up here. These two chapters are not a fully complete
    tkinter reference (which could easily fill a large book by itself),
    but they should be enough to help you get started coding substantial
    Python GUIs. The examples in these chapters are focused on widgets
    and tkinter tools, but Python’s support for code reuse is also
    explored along the way.

  • Chapter 10
    covers more advanced
    GUI programming techniques. It includes an exploration of techniques
    for automating common GUI tasks with Python. Although tkinter is a
    full-featured library, a small amount of reusable Python code can
    make its interfaces even more powerful and easier to use.

  • Chapter 11
    wraps up by
    presenting a handful of complete GUI programs that make use of
    coding and widget techniques presented in the four preceding
    chapters. We’ll learn how to implement text editors, image viewers,
    clocks, and more.

Because GUIs are actually cross-domain tools, other GUI examples
will also show up throughout the remainder of this book. For example,
we’ll later see complete email GUIs and calculators, as well as a basic
FTP client GUI; additional examples such as tree viewers and table
browsers are available externally in the book examples package.
Chapter 11
gives a list of forward pointers to
other tkinter examples in this text.

After we explore GUIs, in
Part IV
we’ll also learn how to build basic user interfaces within a web browser
using HTML and Python scripts that run on a server—a very different
model with advantages and tradeoffs all its own that are important to
understand. Newer technologies such as the RIAs described later in this
chapter build on the web browser model to offer even more interface
choices.

For now, though, our focus here is on more traditional GUIs—known
as “desktop” applications to some, and as “standalone” GUIs to others.
As we’ll see when we meet FTP and email client GUIs in the Internet part
of this book, though, such programs often connect to a network to do
their work as well.

Running the Examples

One other
point I’d like to make right away: most GUIs are dynamic
and interactive interfaces, and the best I can do here is show static
screenshots representing selected states in the interactions such
programs implement. This really won’t do justice to most examples. If
you are not working along with the examples already, I encourage you to
run the GUI examples in this and later chapters on your own.

On Windows,
the standard Python install comes with tkinter support
built in, so all these examples should work immediately. Mac OS X
comes bundled with a tkinter-aware Python as well. For
other systems, Pythons with tkinter support are either provided with the
system itself or are readily available (see the top-level
README-PP4E.txt
file in the book
examples distribution for more details). Getting tkinter to work on your
computer is worth whatever extra install details you may need to absorb,
though; experimenting with these programs is a great way to learn about
both GUI programming and Python itself.

Also see the description of book example portability in general in
this book’s Preface. Although Python and tkinter are both largely
platform neutral, you may run into some minor platform-specific issues
if you try to run this book’s examples on platforms other than that used
to develop this book. Mac OS X, for example, might pose subtle
differences in some of the examples’ operation. Be sure to watch this
book’s website for pointers and possible future patches for using the
examples on other platforms.

Has Anyone Noticed That G-U-I Are the First Three Letters of
“GUIDO”?

Python creator Guido van Rossum
didn’t originally set out to build a GUI development
tool, but Python’s ease of use and rapid turnaround have made this one
of its primary roles. From an implementation perspective, GUIs in
Python are really just instances of C extensions, and extensibility
was one of the main ideas behind Python. When a script builds push
buttons and menus, it ultimately talks to a C library; and when a
script responds to a user event, a C library ultimately talks back to
Python. It’s really just an example of what is possible when Python is
used to script external libraries.

But from a practical point of view, GUIs are a critical part of
modern systems and an ideal domain for a tool like Python. As we’ll
see, Python’s simple syntax and object-oriented flavor blend well with
the GUI model—it’s natural to represent each device drawn on a screen
as a Python class. Moreover, Python’s quick turnaround lets
programmers experiment with alternative layouts and behavior rapidly,
in ways not possible with traditional development techniques. In fact,
you can usually make a change to a Python-based GUI and observe its
effects in a matter of seconds. Don’t try this with C++!

[
23
]
The term “widget set” refers to the objects used to build
familiar point-and-click user interface devices—push buttons,
sliders, input fields, and so on. tkinter comes with Python
classes that correspond to all the widgets you’re accustomed to
seeing in graphical displays. Besides widgets, tkinter also
comes with tools for other activities, such as scheduling events
to occur, waiting for socket data to arrive, and so on.

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

Other books

The Storm Dragon by Paula Harrison
Mystery of the Runaway Ghost by Gertrude Chandler Warner
The Iron Horseman by Kelli Ann Morgan
The Mountain of Light by Indu Sundaresan
TORN by HILL, CASEY
Rise of the Valiant by Morgan Rice
Irresistible? by Stephanie Bond
The Willingness to Burn by J. P. London
Wild Indigo by Judith Stanton
Silicon Valley Sweetheart by St. Claire, Alyssa