''' typeablewindow.py Jeff Ondich, updated 3 November 2018 The TypeableWindow class demonstrates how to handle keyboard events in the context of John Zelle's graphics library. TypeableWindow uses the Tkinter "bind_all" mechanism to trap keyboard events and respond to them appropriately. 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, title, width, height): GraphWin.__init__(self, title, width, height) self.setBackground(color_rgb(255, 255, 255)) self.circle = Circle(Point(width // 2, height // 2), min(width, height) // 4) self.circle.setFill(color_rgb(180, 50, 50)) self.circle.draw(self) self.bind_all('', self.key_handler) self.bind_all('', self.up_handler) self.bind_all('', self.down_handler) self.bind_all('', self.left_handler) self.bind_all('', self.right_handler) def key_handler(self, event): if event.char == 'r': self.circle.setFill(color_rgb(180, 50, 50)) elif event.char == 'g': self.circle.setFill(color_rgb(50, 180, 50)) elif event.char == 'b': self.circle.setFill(color_rgb(50, 50, 180)) def up_handler(self, event): self.circle.move(0, -10) def down_handler(self, event): self.circle.move(0, 10) def right_handler(self, event): self.circle.move(10, 0) def left_handler(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()