Never been to DZone Snippets before?

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

About this user

Korakot Chaovavanich http://korakot.stumbleupon.com

« Newer Snippets
Older Snippets »
Showing 1-2 of 2 total  RSS 

Handle keyboard event easily

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)
   1  
   2  from appuifw import *
   3  from key_codes import *
   4  
   5  class Keyboard(object):
   6      def __init__(self):
   7          self.state = {}  # is this key pressing ?
   8          self.buffer= {}  # is it waiting to be processed ?
   9      def handle_event(self, event): # for event_callback
  10          code = event['scancode']
  11          if event['type'] == EEventKeyDown:
  12              self.buffer[code]= 1   # put into queue
  13              self.state[code] = 1
  14          elif event['type'] == EEventKeyUp:
  15              self.state[code] = 0
  16      def pressing(self, code):      # just check
  17          return self.state.get(code,0)
  18      def pressed(self, code):       # check and process the event
  19          if self.buffer.get(code,0):
  20              self.buffer[code] = 0  # take out of queue
  21              return 1
  22          return 0
  23  
  24  key = Keyboard()
  25  app.body = canvas = Canvas(event_callback=key.handle_event)

Now you can check the keyboard status with key.pressing and key.pressed
   1  
   2  >>> key.state   # just pressed up arrow
   3  {17: 0}
   4  >>> key.buffer
   5  {17: 1}
   6  >>> key.pressing(EScancodeUpArrow)  # it's not pressing
   7  0
   8  >>> key.pressed(EScancodeUpArrow)   # yes, it's pressed
   9  1
  10  >>> key.pressed(EScancodeUpArrow)   # no, you've just processed it
  11  0
  12  >>>

Getting key press

In Pys60 1.2 there are 3 types for app.body, namely
- Canvas
- Text
- Listbox
They can recieve and process key press.
In older versions, they all have a bind method:
   1  bind(event_code, callback)

event codes are defined in key_codes module
You can import some or all of them
   1  from key_codes import EKeyLeftArrow, EKeySelect, EKey9, EKeyEdit
See diagram for 6630.

In the latest version, Canvas gains ability to respond
to events in more details. You can give it 2 callbacks
when creating a Canvas object.
   1  c = Canvas(redraw_callback=None, event_callback=None)

event_callback will get a dict of the key event containing:
- 'type': one of EEventKeyDown, EEventKey, or EEventKeyUp
- 'keycode': the logical key
- 'scancode': the physical key
- 'modifier': probably about Shift, Ctrl ?

The simplest use is to detect when type=EEventKey
and use the 'keycode' value.
For advanced use, look at keyviewer.py example.
« Newer Snippets
Older Snippets »
Showing 1-2 of 2 total  RSS