← 学习库 Think Python 2e 目录

Chapter 20

> 来源: Think Python 2e (Allen B. Downey)

> 原页: https://greenteapress.com/thinkpython/html/thinkpython020.html

\

[插图缺失:thinkpython019.html]
[ [](thinkpython021.html)

------------------------------------------------------------------------

Chapter 19   Case study: Tkinter

19.1   GUI

Most of the programs we have seen so far are text-based, but many programs use graphical user interfaces, also known as GUIs.

Python provides several choices for writing GUI-based programs, including wxPython, Tkinter, and Qt. Each has pros and cons, which is why Python has not converged on a standard.

The one I will present in this chapter is Tkinter because I think it is the easiest to get started with. Most of the concepts in this chapter apply to the other GUI modules, too.

There are several books and web pages about Tkinter. One of the best online resources is An Introduction to Tkinter by Fredrik Lundh.

I have written a module called Gui.py that comes with Swampy. It provides a simplified interface to the functions and classes in Tkinter. The examples in this chapter are based on this module.

Here is a simple example that creates and displays a Gui:

To create a GUI, you have to import Gui from Swampy:

Gui.py007

Or, depending on how you installed Swampy, like this:

Gui.py008

Then instantiate a Gui object:

Gui.py009

When you run this code, a window should appear with an empty gray square and the title Gui. Gui.py01 runs the event loop, which waits for the user to do something and responds accordingly. It is an infinite loop; it runs until the user closes the window, or presses Control-C, or does something that causes the program to quit.

This Gui doesn’t do much because it doesn’t have any widgets. Widgets are the elements that make up a GUI; they include:

Button:

A widget, containing text or an image, that performs an action when pressed.

Canvas:

A region that can display lines, rectangles, circles and other shapes.

Entry:

A region where users can type text.

Scrollbar:

A widget that controls the visible part of another widget.

Frame:

A container, often invisible, that contains other widgets.

The empty gray square you see when you create a Gui is a Frame. When you create a new widget, it is added to this Frame.

19.2   Buttons and callbacks

The method bu creates a Button widget:

Gui.py012

The return value from bu is a Button object. The button that appears in the Frame is a graphical representation of this object; you can control the button by invoking methods on it.

bu takes up to 32 parameters that control the appearance and function of the button. These parameters are called options. Instead of providing values for all 32 options, you can use keyword arguments, like Gui.py015, to specify only the options you need and use the default values for the rest.

When you add a widget to the Frame, it gets “shrink-wrapped;” that is, the Frame shrinks to the size of the Button. If you add more widgets, the Frame grows to accommodate them.

The method bu creates a Label widget:

Gui.py017

By default, Tkinter stacks the widgets top-to-bottom and centers them. We’ll see how to override that behavior soon.

If you press the button, you will see that it doesn’t do much. That’s because you haven’t “wired it up;” that is, you haven’t told it what to do!

The option that controls the behavior of a button is Gui.py0. The value of Gui.py0 is a function that gets executed when the button is pressed. For example, here is a function that creates a new Label:

Gui.py020

Now we can create a button with this function as its command:

Gui.py021

When you press this button, it should execute Gui.py022 and a new label should appear.

The value of the Gui.py0 option is a function object, which is known as a callback because after you call bu to create the button, the flow of execution “calls back” when the user presses the button.

This kind of flow is characteristic of event-driven programming. User actions, like button presses and key strokes, are called events. In event-driven programming, the flow of execution is determined by user actions rather than by the programmer.

The challenge of event-driven programming is to construct a set of widgets and callbacks that work correctly (or at least generate appropriate error messages) for any sequence of user actions.

Exercise 1  

Write a program that creates a GUI with a single button. When the button is pressed it should create a second button. When that button is pressed, it should create a label that says, “Nice job!”.

What happens if you press the buttons more than once? Solution: Gui.py025

19.3   Canvas widgets

One of the most versatile widgets is the Canvas, which creates a region for drawing lines, circles and other shapes. If you did Exercise 4 you are already familiar with canvases.

The method bu creates a new Canvas:

Gui.py027

Gui00 and Gui.py are the dimensions of the canvas in pixels.

After you create a widget, you can still change the values of the options with the Gui.py method. For example, the bu option changes the background color:

Gui.py032

The value of bu is a string that names a color. The set of legal color names is different for different implementations of Python, but all implementations provide at least:

Gui.py034

Shapes on a Canvas are called items. For example, the Canvas method Gui.py draws (you guessed it) a circle:

Gui.py036

The first argument is a coordinate pair that specifies the center of the circle; the second is the radius.

Gui.py provides a standard Cartesian coordinate system with the origin at the center of the Canvas and the positive y axis pointing up. This is different from some other graphics systems where the origin is in the upper left corner, with the y axis pointing down.

The Gui0 option specifies that the circle should be filled in with red.

The return value from Gui.py is an Item object that provides methods for modifying the item on the canvas. For example, you can use Gui.py to change any of the circle’s options:

Gui.py041

Gui00 is the thickness of the outline in pixels; Gui.py0 is the color.

Exercise 2  

Write a program that creates a Canvas and a Button. When the user presses the Button, it should draw a circle on the canvas.

19.4   Coordinate sequences

The Gui.py044 method takes a sequence of coordinates that specify opposite corners of the rectangle. This example draws a blue rectangle with the lower left corner at the origin and the upper right corner at (200,100):

Gui.py045

This way of specifying corners is called a bounding box because the two points bound the rectangle.

Gui0 takes a bounding box and draws an oval within the specified rectangle:

Gui.py047

Gui0 takes a sequence of coordinates and draws a line that connects the points. This example draws two legs of a triangle:

Gui.py049

Gui.py0 takes the same arguments, but it draws the last leg of the polygon (if necessary) and fills it in:

Gui.py051

19.5   More widgets

Tkinter provides two widgets that let users type text: an Entry, which is a single line, and a Text widget, which has multiple lines.

bu creates a new Entry:

Gui.py053

The Gui0 option allows you to put text into the entry when it is created. The Gui method returns the contents of the Entry (which may have been changed by the user):

Gui.py056

bu creates a Text widget:

Gui.py058

Gui00 and Gui.py are the dimensions of the widget in characters and lines.

Gui.py puts text into the Text widget:

Gui.py062

Gui is a special index that indicates the last character in the Text widget.

You can also specify a character using a dotted index, like Gui, which has the line number before the dot and the column number after. The following example adds the letters Gui.py06 after the first character of the first line.

Gui.py066

The Gui method reads the text in the widget; it takes a start and end index as arguments. The following example returns all the text in the widget, including the newline character:

Gui.py068

The Gui.py method removes text from the widget; the following example deletes all but the first two characters:

Gui.py070

Exercise 3  

Modify your solution to Exercise 2 by adding an Entry widget and a second button. When the user presses the second button, it should read a color name from the Entry and use it to change the fill color of the circle. Use Gui.py to modify the existing circle; don’t create a new one.

Your program should handle the case where the user tries to change the color of a circle that hasn’t been created, and the case where the color name is invalid.

You can see my solution at Gui.py072.

19.6   Packing widgets

So far we have been stacking widgets in a single column, but in most GUIs the layout is more complicated. For example, Figure 19.1 shows a simplified version of TurtleWorld (see Chapter 4).


[插图缺失:thinkpython028.png]

Figure 19.1: TurtleWorld after running the snowflake code.


This section presents the code that creates this GUI, broken into a series of steps. You can download the complete example from Gui.py073.

At the top level, this GUI contains two widgets—a Canvas and a Frame—arranged in a row. So the first step is to create the row.

Gui.py074

Gui00 is the function that creates and arranges the widgets. Arranging widgets in a GUI is called packing.

Gui creates a row Frame and makes it the “current Frame.” Until this Frame is closed or another Frame is created, all subsequent widgets are packed in a row.

Here is the code that creates the Canvas and the column Frame that hold the other widgets:

Gui.py077

The first widget in the column is a grid Frame, which contains four buttons arranged two-by-two:

Gui.py078

bu creates the grid; the argument is the number of columns. Widgets in the grid are laid out left-to-right, top-to-bottom.

The first button uses Gui.py080 as a callback; the second uses Gui.py081. These are bound methods, which means they are associated with a particular object. When they are invoked, they are invoked on the object.

The next widget in the column is a row Frame that contains a Button and an Entry:

Gui.py082

The first argument to Gui is a list of weights that determines how extra space is allocated between widgets. The list Gui00 means that all extra space is allocated to the second widget, which is the Entry. If you run this code and resize the window, you will see that the Entry grows and the Button doesn’t.

The option Gui0 “pads” this row in the y direction, adding 30 pixels of space above and below.

Gui.py ends this row of widgets, so subsequent widgets are packed in the column Frame. Gui.py keeps a stack of Frames:

The method Gui.py09 reads the contents of the Entry, uses it as a filename, reads the contents and passes it to Gui.py09. Gui.py096 is an Interpreter object that knows how to take a string and execute it as Python code.

Gui.py097

The last two widgets are a Text widget and a Button:

Gui.py098

Gui.py09 is similar to Gui.py10 except that it takes the code from the Text widget instead of from a file:

Gui.py101

Unfortunately, the details of widget layout are different in other languages, and in different Python modules. Tkinter alone provides three different mechanisms for arranging widgets. These mechanisms are called geometry managers. The one I demonstrated in this section is the “grid” geometry manager; the others are called “pack” and “place”.

Fortunately, most of the concepts in this section apply to other GUI modules and other languages.

A Menubutton is a widget that looks like a button, but when pressed it pops up a menu. After the user selects an item, the menu disappears.

Here is code that creates a color selection Menubutton (you can download it from Gui.py102):

Gui.py103

bu creates the Menubutton. Initially, the text on the button is the name of the default color. The following loop creates one menu item for each color:

Gui.py105

The first argument of bu is the Menubutton these items are associated with.

The Gui.py1 option is a Callable object, which is something new. So far we have seen functions and bound methods used as callbacks, which works fine if you don’t have to pass any arguments to the function. Otherwise you have to construct a Callable object that contains a function, like Gui.py108, and its arguments, like Gui00.

The Callable object stores a reference to the function and the arguments as attributes. Later, when the user clicks on a menu item, the callback calls the function and passes the stored arguments.

Here is what Gui.py110 might look like:

Gui.py111

When the user selects a menu item and Gui.py112 is called, it configures the Menubutton to display the newly-selected color. It also print the color; if you try this example, you can confirm that Gui.py113 is called when you select an item (and not called when you create the Callable object).

19.8   Binding

A binding is an association between a widget, an event and a callback: when an event (like a button press) happens on a widget, the callback is invoked.

Many widgets have default bindings. For example, when you press a button, the default binding changes the relief of the button to make it look depressed. When you release the button, the binding restores the appearance of the button and invokes the callback specified with the Gui.py1 option.

You can use the Gui0 method to override these default bindings or to add new ones. For example, this code creates a binding for a canvas (you can download the code in this section from Gui.py116):

Gui.py117

The first argument is an event string; this event is triggered when the user presses the left mouse button. Other mouse events include Gui.py118, Gui.py119 and Gui.py120.

The second argument is an event handler. An event handler is a function or bound method, like a callback, but an important difference is that an event handler takes an Event object as a parameter. Here is an example:

Gui.py121

The Event object contains information about the type of event and details like the coordinates of the mouse pointer. In this example the information we need is the location of the mouse click. These values are in “pixel coordinates,” which are defined by the underlying graphical system. The method Gui.py122 translates them to “Canvas coordinates,” which are compatible with Canvas methods like Gui.py.

For Entry widgets, it is common to bind the Gui.py124 event, which is triggered when the user presses the Return or Enter key. For example, the following code creates a Button and an Entry.

Gui.py125

Gui.py126 is called when the Button is pressed or when the user hits Return while typing in the Entry. To make this work, we need a function that can be called as a command (with no arguments) or as an event handler (with an Event as an argument):

Gui.py127

Gui.py128 gets the contents of the Entry and displays it as a Text item in the Canvas.

It is also possible to create bindings for Canvas items. The following is a class definition for Gui.py129, which is a child class of Gui0 that provides bindings that implement drag-and-drop capability.

Gui.py131

The init method takes an Item as a parameter. It copies the attributes of the Item and then creates bindings for three events: a button press, button motion, and button release.

The event handler Gui.py stores the coordinates of the current event and the original color of the item, then changes the color to yellow:

Gui.py133

Gui0 stands for “get configuration;” it takes the name of an option as a string and returns the current value of that option.

Gui0 computes how far the object has moved relative to the starting place, updates the stored coordinates, and then moves the item.

Gui.py136

This computation is done in pixel coordinates; there is no need to convert to Canvas coordinates.

Finally, Gui0 restores the original color of the item:

Gui.py138

You can use the Gui.py139 class to add drag-and-drop capability to an existing item. For example, here is a modified version of Gui.py140 that uses Gui.py to create an Item and Gui.py142 to make it draggable:

Gui.py143

This example demonstrates one of the benefits of inheritance: you can modify the capabilities of a parent class without modifying its definition. This is particularly useful if you want to change behavior defined in a module you did not write.

19.9   Debugging

One of the challenges of GUI programming is keeping track of which things happen while the GUI is being built and which things happen later in response to user events.

For example, when you are setting up a callback, it is a common error to call the function rather than passing a reference to it:

Gui.py144

If you run this code, you will see that it calls Gui.py145 immediately, and then creates the button. When you press the button, it does nothing because the return value from Gui.py146 is Gui0. Usually you do not want to invoke a callback while you are setting up the GUI; it should only be invoked later in response to a user event.

Another challenge of GUI programming is that you don’t have control of the flow of execution. Which parts of the program execute and their order are determined by user actions. That means that you have to design your program to work correctly for any possible sequence of events.

For example, the GUI in Exercise 3 has two widgets: one creates a Circle item and the other changes the color of the Circle. If the user creates the circle and then changes its color, there’s no problem. But what if the user changes the color of a circle that doesn’t exist yet? Or creates more than one circle?

As the number of widgets grows, it is increasingly difficult to imagine all possible sequences of events. One way to manage this complexity is to encapsulate the state of the system in an object and then consider:

You might also find it useful to define, and check, invariants that should hold regardless of the sequence of events.

This approach to GUI programming can help you write correct code without taking the time to test every possible sequence of user events!

19.10   Glossary

GUI:

A graphical user interface.

widget:

One of the elements that makes up a GUI, including buttons, menus, text entry fields, etc.

option:

A value that controls the appearance or function of a widget.

keyword argument:

An argument that indicates the parameter name as part of the function call.

callback:

A function associated with a widget that is called when the user performs an action.

bound method:

A method associated with a particular instance.

event-driven programming:

A style of programming in which the flow of execution is determined by user actions.

event:

A user action, like a mouse click or key press, that causes a GUI to respond.

event loop:

An infinite loop that waits for user actions and responds.

item:

A graphical element on a Canvas widget.

bounding box:

A rectangle that encloses a set of items, usually specified by two opposing corners.

pack:

To arrange and display the elements of a GUI.

geometry manager:

A system for packing widgets.

binding:

An association between a widget, an event, and an event handler. The event handler is called when the event occurs in the widget.

19.11   Exercises

Exercise 4  

For this exercise, you will write an image viewer. Here is a simple example:

Gui.py148

Gui.py149 reads a file and returns a Gui.py150 object that Tkinter can display. Gui.py151 puts the image on the canvas, centered on the given coordinates. You can also put images on labels, buttons, and some other widgets:

Gui.py152

PhotoImage can only handle a few image formats, like GIF and PPM, but we can use the Python Imaging Library (PIL) to read other files.

The name of the PIL module is Gui00, but Tkinter defines an object with the same name. To avoid the conflict, you can use Gui.py154 like this:

Gui.py155

The first line imports Gui00 and gives it the local name Gui. The second line imports Gui.py1, which can translate a PIL image into a Tkinter PhotoImage. Here’s an example:

Gui.py159

  1. Download Gui.py160, Gui.py161 and Gui.py162 from Gui.py163. Run Gui.py164. You might have to install Gui and Gui.py1. They are probably in your software repository, but if not you can get them from Gui.py167.
  2. In Gui.py168 change the name of the second PhotoImage from Gui.py to Gui00 and run the program again. You should see the second PhotoImage but not the first.

    The problem is that when you reassign Gui00 it overwrites the reference to the first PhotoImage, which then disappears. The same thing happens if you assign a PhotoImage to a local variable; it disappears when the function ends.

    To avoid this problem, you have to store a reference to each PhotoImage you want to keep. You can use a global variable, or store PhotoImages in a data structure or as an attribute of an object.

    This behavior can be frustrating, which is why I am warning you (and why the example image says “Danger!”).

  3. Starting with this example, write a program that takes the name of a directory and loops through all the files, displaying any files that PIL recognizes as images. You can use a Gui statement to catch the files PIL doesn’t recognize.

    When the user clicks on the image, the program should display the next one.

  4. PIL provides a variety of methods for manipulating images. You can read about them at Gui.py173. As a challenge, choose a few of these methods and provide a GUI for applying them to images.

Solution: Gui.py174.

Exercise 5  

A vector graphics editor is a program that allows users to draw and edit shapes on the screen and generate output files in vector graphics formats like Postscript and SVG.

Write a simple vector graphics editor using Tkinter. At a minimum, it should allow users to draw lines, circles and rectangles, and it should use Gui.py175 to generate a Postscript description of the contents of the Canvas.

As a challenge, you could allow users to select and resize items on the Canvas.

Exercise 6  

Use Tkinter to write a basic web browser. It should have a Text widget where the user can enter a URL and a Canvas to display the contents of the page.

You can use the Gui.py module to download files (see Exercise 6) and the Gui.py177 module to parse the HTML tags (see Gui.py178).

At a minimum your browser should handle plain text and hyperlinks. As a challenge you could handle background colors, text formatting tags and images.

Contribute

If you would like to make a contribution to support my books, you can use the button below. Thank you!

Pay what you want:

Small $1.00 USD Medium $5.00 USD Large $10.00 USD X-Large $20.00 USD XX-Large $50.00 USD

Are you using one of our books in a class?

We'd like to know about it. Please consider filling out this short survey.


------------------------------------------------------------------------

\

[插图缺失:thinkpython019.html]
[ [](thinkpython021.html)

---

← Chapter 19Chapter 21 →