16

I can bind an event to a textctrl box np. The problem is I have to be clicked inside of the textctrl box to "catch" this event. I am hoping to be able to catch anytime someone presses the Arrow keys while the main window has focus.

NOT WORKING:

 wx.EVT_KEY_DOWN(self, self.OnKeyDown)

WORKING:

self.NudgeTxt = wx.TextCtrl(self.panel, size=(40,20), value=str(5))
wx.EVT_KEY_DOWN(self.NudgeTxt, self.OnKeyDown)

I am pretty sure I am missing something easy. However am a bit stuck.

1
  • sorry, how do you bind the key down event to the text box? cos that's just what I need! wx.EVT_KEY_DOWN(self.NudgeTxt, self.OnKeyDown) doesn't seem to work for me
    – phunehehe
    Nov 9, 2010 at 8:15

2 Answers 2

21

Instead try binding to wx.EVT_CHAR_HOOK

e.g..

self.Bind(wx.EVT_CHAR_HOOK, self.onKey)

  ...

def onKey(self, evt):
    if evt.GetKeyCode() == wx.WXK_DOWN:
        print "Down key pressed"
    else:
        evt.Skip()
1
  • This allowed my main window to see the event, but my children don't see it. All of my handlers include event.Skip(). Any suggestions?
    – kjgregory
    Oct 23, 2015 at 15:05
4

You could use EVT_CHAR_HOOK,

    self.Bind(wx.EVT_CHAR_HOOK, self.hotkey)


def hotkey(self, event):
    code = event.GetKeyCode()
    if code == wx.WXK_LEFT:  # or whatever...
        ...

or use an accelerator table

    ac = [(wx.ACCEL_NORMAL, wx.WXK_LEFT, widget.GetId())]
    tbl = wx.AcceleratorTable(ac)
    self.SetAcceleratorTable(tbl)

you'll need to use a button or widgets' ID in the accelerator table, and pressing the button will trigger the widgets' event handler.

If you have no widgets that you'd like their events to be triggered, and would rather some kind of "invisible" widget that has event bindings, then you can do this:

    ac = []
    keys = [wx.WXK_LEFT, wx.WXK_RIGHT, wx.WXK_UP, wx.WXK_DOWN]
    for key in keys:
        _id = wx.NewId()
        ac.append((wx.ACCEL_NORMAL, key, _id))
        self.Bind(wx.EVT_MENU, self.your_function_to_call, id=_id)

    tbl = wx.AcceleratorTable(ac)
    self.SetAcceleratorTable(tbl)

I iterate over the interested keys to bind to, and create new widgets IDs for them. I then use these IDs to bind menu items to (which accelerator keys trigger) and use these IDs in the accelerator table's list of tuples.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.