Search code examples
macoscocoapyobjc

Arrow key event handling in PyObjC


I am trying to make an app using PyObjC and am struggling to find how to record arrow key (left and right). I would like to be able to record every time the user presses the left and right arrow keys. I am using another example found online. Instead of the buttons used in previous example for increment and detriment, I would like to use the arrow keys on the key board. Been looking a while and thought I could get some help here. Thanks!

from Cocoa import *
from Foundation import NSObject

class TAC_UI_Controller(NSWindowController):
counterTextField = objc.IBOutlet()

def windowDidLoad(self):
    NSWindowController.windowDidLoad(self)

    # Start the counter
    self.count = 0

@objc.IBAction
def increment_(self, sender):
    self.count += 1
    self.updateDisplay()

@objc.IBAction
def decrement_(self, sender):
    self.count -= 1
    self.updateDisplay()

def updateDisplay(self):
    self.counterTextField.setStringValue_(self.count)

if __name__ == "__main__":
app = NSApplication.sharedApplication()

# Initiate the contrller with a XIB
viewController = test.alloc().initWithWindowNibName_("test")

# Show the window
viewController.showWindow_(viewController)

# Bring app to top
NSApp.activateIgnoringOtherApps_(True)

from PyObjCTools import AppHelper
AppHelper.runEventLoop()        

Solution

  • Your NSView-derived class should implement a keyDown_ and / or keyUp_. You also need to have acceptsFirstResponder return True:

    from AppKit import NSView
    
    class MyView(NSView)
    
        def keyDown_(self, event):
            pass
    
        def keyUp_(self, event):
            pass
    
    def acceptsFirstResponder(self):           
        return True      
    

    Here'a an example implementation from the PyObjC documentation you can use: https://pythonhosted.org/pyobjc/examples/Cocoa/AppKit/DragItemAround/index.html