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

(yzsuai) #1

window show up as black on red, with a large Courier font. You’ll have to take my
word for it (or run this on your own).


But the main point of this example is to demonstrate other kinds of event binding
protocols at work. We saw a script that intercepted left and double-left mouse clicks
with the widget bind method in Chapter 7, using event names and


; the script here demonstrates other kinds of events that are commonly
caught with bind:

To catch the press of a single key on the keyboard, register a handler for the
event identifier; this is a lower-level way to input data in GUI programs
than the Entry widget covered in the next section. The key pressed is returned in
ASCII string form in the event object passed to the callback handler (event.char).
Other attributes in the event structure identify the key pressed in lower-level detail.
Key presses can be intercepted by the top-level root window widget or by a widget
that has been assigned keyboard focus with the focus method used by this script.

This script also catches mouse motion while a button is held down: the registered
event handler is called every time the mouse is moved while the left
button is pressed and receives the current X/Y coordinates of the mouse pointer in
its event argument (event.x, event.y). Such information can be used to implement
object moves, drag-and-drop, pixel-level painting, and so on (e.g., see the PyDraw
examples in Chapter 11).
,
This script also catches right and middle mouse button clicks (known as buttons
3 and 2). To make the middle button 2 click work on a two-button mouse, try
clicking both buttons at the same time; if that doesn’t work, check your mouse
setting in your properties interface (the Control Panel on Windows).
,
To catch more specific kinds of key presses, this script registers for the Return/
Enter and up-arrow key press events; these events would otherwise be routed to
the general handler and require event analysis.

Here is what shows up in the stdout output stream after a left click, right click, left click
and drag, a few key presses, a Return and up-arrow press, and a final double-left click
to exit. When you press the left mouse button and drag it around on the display, you’ll
get lots of drag event messages; one is printed for every move during the drag (and one
Python callback is run for each):


C:\...\PP4E\Gui\Tour> python bind.py
Got left mouse button click: Widget=.25763696 X=376 Y=53
Got right mouse button click: Widget=.25763696 X=36 Y=60
Got left mouse button click: Widget=.25763696 X=144 Y=43
Got left mouse button drag: Widget=.25763696 X=144 Y=45
Got left mouse button drag: Widget=.25763696 X=144 Y=47

Binding Events | 445
Free download pdf