Binding Events

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

Example 7-15. PP2E\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): 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:', showPosEvent(event) def onRightClick(event): print 'Got right mouse button click:', showPosEvent(event) def onMiddleClick(event): print 'Got middle mouse button click:', showPosEvent(event) showAllEvent(event) def onLeftDrag(event): print 'Got left mouse button drag:', showPosEvent(event) def onDoubleLeftClick(event): print 'Got double left mouse click', 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('<Button-1>', ...

Get Programming Python, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.