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

(yzsuai) #1

We’ll see how to build form-like dialogs with labels and input fields later in this chapter
when we meet Entry, and again when we study the grid manager in Chapter 9. For
more custom dialog examples, see ShellGui (Chapter 10), PyMailGUI (Chapter 14),
PyCalc (Chapter 19), and the nonmodal form.py (Chapter 12). Here, we’re moving on
to learn more about events that will prove to be useful currency at later tour
destinations.


Binding Events


We met the bind widget method in the prior chapter, when we used it to catch button
presses in the tutorial. Because bind is commonly used in conjunction with other widg-
ets (e.g., to catch return key presses for input boxes), we’re going to make a stop early
in the tour here as well. Example 8-15 illustrates more bind event protocols.


Example 8-15. PP4E\Gui\Tour\bind.py


from tkinter import *


def showPosEvent(event):
print('Widget=%s X=%s Y=%s' % (event.widget, event.x, event.y))


def showAllEvent(event):
print(event)
for attr in dir(event):
if not attr.startswith('__'):
print(attr, '=>', getattr(event, attr))


def onKeyPress(event):
print('Got key press:', event.char)


def onArrowKey(event):
print('Got up arrow key press')


def onReturnKey(event):
print('Got return key press')


def onLeftClick(event):
print('Got left mouse button click:', end=' ')
showPosEvent(event)


def onRightClick(event):
print('Got right mouse button click:', end=' ')
showPosEvent(event)


def onMiddleClick(event):
print('Got middle mouse button click:', end=' ')
showPosEvent(event)
showAllEvent(event)


def onLeftDrag(event):
print('Got left mouse button drag:', end=' ')
showPosEvent(event)


Binding Events | 443
Free download pdf