[Python编程(第4版)].(Programming.Python.4th.Edition).Mark.Lutz.文字版

(yzsuai) #1

cases, the slideshows run independently but are based on after events fired from the
same single event loop in a single process.


PyDraw: Painting and Moving Graphics


Chapter 9 introduced simple tkinter animation techniques (see the tour’s canvasDraw
variants). The PyDraw program listed here builds upon those ideas to implement a
more feature-rich painting program in Python. It adds new trails and scribble drawing
modes, object and background color fills, embedded photos, and more. In addition, it
implements object movement and animation techniques—drawn objects may be
moved around the canvas by clicking and dragging, and any drawn object can be grad-
ually moved across the screen to a target location clicked with the mouse.


Running PyDraw


PyDraw is essentially a tkinter canvas with keyboard and mouse event bindings to allow
users to perform common drawing operations. This isn’t a professional-grade paint
program, but it’s fun to play with. In fact, you really should—it is impossible to capture
things such as object motion in this book. Start PyDraw from the launcher bars (or run
the file movingpics.py from Example 11-8 directly). Press the? key to view a help mes-
sage giving available commands (or read the help string in the code listings).


Figure 11-17 shows PyDraw after a few objects have been drawn on the canvas. To
move any object shown here, either click it with the middle mouse button and drag to
move it with the mouse cursor, or middle-click the object, and then right-click in the
spot you want it to move toward. In the latter case, PyDraw performs an animated
(gradual) movement of the object to the target spot. Try this on the picture shown near
the top of the figure—it will slowly move across your display.


Press “p” to insert photos, and use left-button drags to draw shapes. (Note to Windows
users: middle-click is often either both mouse buttons at once or a scroll wheel, but
you may need to configure this in your control panel.) In addition to mouse events,
there are 17 key-press commands for tailoring sketches that I won’t cover here. It takes
a while to get the hang of what all the keyboard and mouse commands do, but once
you’ve mastered the bindings, you too can begin generating senseless electronic artwork
such as that in Figure 11-18.


PyDraw Source Code


Like PyEdit, PyDraw lives in a single file. Two extensions that customize motion im-
plementations are listed following the main module shown in Example 11-8.


738 | Chapter 11: Complete GUI Programs

Free download pdf