2012年6月13日 星期三

Python wxwidgets bind key 做法 class 版

wx_tools.py
class Key(object):
    '''A key combination.'''

    def __init__(self, key_code, cmd=False, alt=False, shift=False):

        self.key_code = key_code
        '''The numerical code of the pressed key.'''

        self.cmd = cmd
        '''Flag saying whether the ctrl/cmd key was pressed.'''

        self.alt = alt
        '''Flag saying whether the alt key was pressed.'''

        self.shift = shift
        '''Flag saying whether the shift key was pressed.'''

    @staticmethod
    def get_from_key_event(event):
        '''Construct a Key from a wx.EVT_KEY_DOWN event.'''
        return Key(event.GetKeyCode(), event.CmdDown(),
                   event.AltDown(), event.ShiftDown())

    def __hash__(self):
        return hash(tuple(sorted(tuple(vars(self)))))

    def __eq__(self, other):
        if not isinstance(other, Key):
            return NotImplemented
        return self.key_code == other.key_code and \
            self.cmd == other.cmd and \
            self.shift == other.shift and \
            self.alt == other.alt


 main.py
from wx_tools import Key

class MyApp(wx.App):

    def __init_key_handlers(self):
        '''Initialize key shortcuts.'''

        self.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown)

        # Now you define handlers for various keys:

        def bypass_key():
            print 'key bypassed'

        # This is the big dict that maps keys to their handlers:

        self.key_handlers = {
            Key(wx.WXK_ESCAPE): bypass_key,
            Key(wx.WXK_DELETE): bypass_key,
        }

    def init_frame(self):
        self.res = xrc.XmlResource('login.xrc')

        self.frame = self.res.LoadFrame(None, 'mainFrame')

        # bind key event
        self.__init_key_handlers()

        self.frame.Show()

    def OnKeyDown(self, event):
        '''wx.EVT_KEY_DOWN handler.'''
        key = Key.get_from_key_event(event)
        handler = self.key_handlers.get(key, None)
        if handler:
            handler()
        else:
            event.Skip()




Reference :
Processing key events in a strategy pattern - wxPyWiki

沒有留言:

張貼留言