DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Handle Keyboard Event Easily

02.09.2006
| 17091 views |
  • submit to reddit
        I found a code that simplify keyboard event handling
from the popular pys60 tutorial.
I simplify it a bit (removing some feature but make it easier to read)
from appuifw import *
from key_codes import *

class Keyboard(object):
    def __init__(self):
        self.state = {}  # is this key pressing ?
        self.buffer= {}  # is it waiting to be processed ?
    def handle_event(self, event): # for event_callback
        code = event['scancode']
        if event['type'] == EEventKeyDown:
            self.buffer[code]= 1   # put into queue
            self.state[code] = 1
        elif event['type'] == EEventKeyUp:
            self.state[code] = 0
    def pressing(self, code):      # just check
        return self.state.get(code,0)
    def pressed(self, code):       # check and process the event
        if self.buffer.get(code,0):
            self.buffer[code] = 0  # take out of queue
            return 1
        return 0

key = Keyboard()
app.body = canvas = Canvas(event_callback=key.handle_event)
Now you can check the keyboard status with key.pressing and key.pressed
>>> key.state   # just pressed up arrow
{17: 0}
>>> key.buffer
{17: 1}
>>> key.pressing(EScancodeUpArrow)  # it's not pressing
0
>>> key.pressed(EScancodeUpArrow)   # yes, it's pressed
1
>>> key.pressed(EScancodeUpArrow)   # no, you've just processed it
0
>>>