'''The TypeableWindow class demonstrates how to handle keyboard events. Jeff Ondich, 25 Feb 2007 This sample class uses the Tkinter "bind_all" mechanism to trap keyboard events and respond to them appropriately. The TypeableWindow class inherits from John Zelle's GraphWin class, so to use this sample, you need to have Zelle's "graphics" module. The discussion of Events and Bindings in the Tkinter library at http://www.pythonware.com/library/tkinter/introduction/events-and-bindings.htm describes more things you can do to handle keyboard events. ''' from graphics import * class TypeableWindow(GraphWin): def __init__(self, *args): GraphWin.__init__(self, *args) self.setBackground(color_rgb(255, 255, 255)) self.circle = Circle(Point(500, 500), 50) self.circleColor = color_rgb(200, 20, 20) self.circle.setFill(self.circleColor) self.circle.draw(self) self.bind_all('r', self.redHandler) self.bind_all('g', self.greenHandler) self.bind_all('b', self.blueHandler) self.bind_all('', self.upHandler) self.bind_all('', self.downHandler) self.bind_all('', self.leftHandler) self.bind_all('', self.rightHandler) def redHandler(self, event): self.circle.setFill(color_rgb(200, 20, 20)) def greenHandler(self, event): self.circle.setFill(color_rgb(20, 200, 20)) def blueHandler(self, event): self.circle.setFill(color_rgb(20, 20, 200)) def upHandler(self, event): self.circle.move(0, -10) def downHandler(self, event): self.circle.move(0, 10) def rightHandler(self, event): self.circle.move(10, 0) def leftHandler(self, event): self.circle.move(-10, 0) if __name__ == '__main__': print 'Use the arrow keys to move the circle around.' print 'Type r, g, or b to change its color.' window = TypeableWindow('Keyboard Test', 1000, 600) while window.winfo_exists(): window.update()