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

(yzsuai) #1

def onDoubleLeftClick(event):
print('Got double left mouse click', end=' ')
showPosEvent(event)
tkroot.quit()


tkroot = Tk()
labelfont = ('courier', 20, 'bold') # family, size, style
widget = Label(tkroot, text='Hello bind world')
widget.config(bg='red', font=labelfont) # red background, large font
widget.config(height=5, width=20) # initial size: lines,chars
widget.pack(expand=YES, fill=BOTH)


widget.bind('', onLeftClick) # mouse button clicks
widget.bind('', onRightClick)
widget.bind('', onMiddleClick) # middle=both on some mice
widget.bind('', onDoubleLeftClick) # click left twice
widget.bind('', onLeftDrag) # click left and move


widget.bind('', onKeyPress) # all keyboard presses
widget.bind('', onArrowKey) # arrow button pressed
widget.bind('', onReturnKey) # return/enter key pressed
widget.focus() # or bind keypress to tkroot
tkroot.title('Click Me')
tkroot.mainloop()


Most of this file consists of callback handler functions triggered when bound events
occur. As we learned in Chapter 7, this type of callback receives an event object argu-
ment that gives details about the event that fired. Technically, this argument is an
instance of the tkinter Event class, and its details are attributes; most of the callbacks
simply trace events by displaying relevant event attributes.


When run, this script makes the window shown in Figure 8-20; it’s mostly intended
just as a surface for clicking and pressing event triggers.


Figure 8-20. A bind window for the clicking


The black-and-white medium of the book you’re holding won’t really do justice to this
script. When run live, it uses the configuration options shown earlier to make the


444 | Chapter 8: A tkinter Tour, Part 1

Free download pdf