Amy D
Amy D

Reputation: 61

Is there an easy way to capture all Frame/Window keystrokes in Python or wxPython

I tried EVT_KEY_DOWN but doesn't work. Is there a way to capture any keystroke such as F1, F2 , ENTER, and others. I am using a Frame and Panel.

Upvotes: 6

Views: 1331

Answers (3)

Aitch
Aitch

Reputation: 942

Is this what you mean? You need to look at Global Accelerators. By coincidence I've been looking at this the last day or two as well. Assuming the wxpython app window has focus, the following should call appropriate routine on keypress. Working on my ubuntu 11.04 / py 2.7.1 / wxpython 2.8

Clearly you could potentially consolidate the event method if required.

There is not much to be found on this topic but this link and this link helped me out (same website)

import wx

class MyFrame(wx.Frame):

    def __init__(self):
        wx.Frame.__init__(self, None, wx.ID_ANY, "Global Keypress")
        self.panel = wx.Panel(self, wx.ID_ANY)
        self.CreateStatusBar()

        # Global accelerators

        id_F1 = wx.NewId()
        id_F2 = wx.NewId()

        self.Bind(wx.EVT_MENU, self.pressed_F1, id=id_F1)
        self.Bind(wx.EVT_MENU, self.pressed_F2, id=id_F2)

        accel_tbl = wx.AcceleratorTable([
            (wx.ACCEL_NORMAL, wx.WXK_F1, id_F1 ),
            (wx.ACCEL_NORMAL, wx.WXK_F2, id_F2 )
        ])
        self.SetAcceleratorTable(accel_tbl)  

    def pressed_F1(self, event):
        print "Pressed F1"
        return True

    def pressed_F2(self, event):
        print "Pressed F2"
        return True

if __name__ == "__main__":
    app = wx.PySimpleApp()
    f = MyFrame().Show()
    app.MainLoop()

Upvotes: 3

bstpierre
bstpierre

Reputation: 31206

I used EVT_KEY_DOWN in a dialog subclass. In the __init__ method of your dialog class, bind to EVT_KEY_DOWN:

def __init__(self, ....):
    # ...other init code...
    self.Bind(wx.wx.EVT_KEY_UP, self.handle_key_up)

Then provide a method on your dialog like:

def handle_key_up(self, event):
    keycode = event.GetKeyCode()
    lc = self.list_ctrl_fields

    # handle F2
    if keycode == wx.WXK_F2:
        print "got F2"

(Tested in python 2.6, wxPython 2.8.10.)

Upvotes: 3

Related Questions