''' keybinding.py Jeff Ondich, 4 March 2010 This program gives a simple example of how to trap any keystroke in a single handler method. By using the '' parameter to bind_all, you can have every keystroke call your handler, which in turn can use event.char or event.keysym to decide what to do based on the particular character that got typed. In this example, I've shown how to build up a word one keystroke at a time, and then do something with that word after the user hits Return. Compare this program to typeablewindow.py, where I bind each specific character to a separate handler. Both techniques can be great, but sometimes one is more convenient than the other. ''' from graphics import * class WordWindow(GraphWin): def __init__(self, *args): GraphWin.__init__(self, *args) self.setBackground(color_rgb(255, 255, 255)) self.wordInProgress = '' self.finishedWord = '' self.wordInProgressCaption = Text(Point(100, 100), 'Word so far:') self.wordInProgressCaption.setSize(24) self.wordInProgressCaption.draw(self) self.wordInProgressText = Text(Point(400, 100), '') self.wordInProgressText.setSize(24) self.wordInProgressText.draw(self) self.finishedWordCaption = Text(Point(100, 200), 'Completed word:') self.finishedWordCaption.setSize(24) self.finishedWordCaption.draw(self) self.finishedWordText = Text(Point(400, 200), '') self.finishedWordText.setSize(24) self.finishedWordText.draw(self) self.bind_all('', self.keyHandler) self.bind_all('', self.returnHandler) def keyHandler(self, event): if event.keysym != 'Return': self.wordInProgress += event.char self.wordInProgressText.setText(self.wordInProgress) def returnHandler(self, event): self.finishedWord = self.wordInProgress self.finishedWordText.setText(self.finishedWord) self.wordInProgress = '' self.wordInProgressText.setText('') if __name__ == '__main__': window = TypeableWindow('Keyboard Test', 1000, 600) while window.winfo_exists(): window.update()