Wrappers for the Cocoa frameworks on macOS
—
The Cocoa user interface framework providing comprehensive APIs for building native macOS applications. AppKit includes windows, views, controls, event handling, graphics, and all the components needed for rich desktop application development.
Helper functions for common AppKit development tasks and convenient access to application-wide functionality.
def NSDictionaryOfVariableBindings(*names):
"""
Creates a dictionary mapping variable names to their values from the calling scope.
Commonly used with Auto Layout visual format language.
Args:
*names (str): Variable names to include in dictionary
Returns:
dict: Dictionary with names as keys and variable values as values
Example:
button1 = NSButton.alloc().init()
button2 = NSButton.alloc().init()
views = NSDictionaryOfVariableBindings("button1", "button2")
# Returns: {"button1": button1, "button2": button2}
"""Global access to the shared application instance for application-wide operations and event handling.
NSApp: object # Singleton NSApplication instance, equivalent to NSApplication.sharedApplication()Special character constants for keyboard input handling, converted to Python strings for convenient use in event processing and key binding systems.
# Basic input characters
NSEnterCharacter: str # Enter/Return key character
NSBackspaceCharacter: str # Backspace key character
NSTabCharacter: str # Tab key character
NSNewlineCharacter: str # Newline character
NSFormFeedCharacter: str # Form feed character
NSCarriageReturnCharacter: str # Carriage return character
NSBackTabCharacter: str # Back tab (Shift+Tab) character
NSDeleteCharacter: str # Delete key character
NSLineSeparatorCharacter: str # Line separator character
NSParagraphSeparatorCharacter: str # Paragraph separator character
# Function keys F1-F35
NSF1FunctionKey: str # F1 function key
NSF2FunctionKey: str # F2 function key
NSF3FunctionKey: str # F3 function key
NSF4FunctionKey: str # F4 function key
NSF5FunctionKey: str # F5 function key
NSF6FunctionKey: str # F6 function key
NSF7FunctionKey: str # F7 function key
NSF8FunctionKey: str # F8 function key
NSF9FunctionKey: str # F9 function key
NSF10FunctionKey: str # F10 function key
NSF11FunctionKey: str # F11 function key
NSF12FunctionKey: str # F12 function key
NSF13FunctionKey: str # F13 function key
NSF14FunctionKey: str # F14 function key
NSF15FunctionKey: str # F15 function key
NSF16FunctionKey: str # F16 function key
NSF17FunctionKey: str # F17 function key
NSF18FunctionKey: str # F18 function key
NSF19FunctionKey: str # F19 function key
NSF20FunctionKey: str # F20 function key
NSF21FunctionKey: str # F21 function key
NSF22FunctionKey: str # F22 function key
NSF23FunctionKey: str # F23 function key
NSF24FunctionKey: str # F24 function key
NSF25FunctionKey: str # F25 function key
NSF26FunctionKey: str # F26 function key
NSF27FunctionKey: str # F27 function key
NSF28FunctionKey: str # F28 function key
NSF29FunctionKey: str # F29 function key
NSF30FunctionKey: str # F30 function key
NSF31FunctionKey: str # F31 function key
NSF32FunctionKey: str # F32 function key
NSF33FunctionKey: str # F33 function key
NSF34FunctionKey: str # F34 function key
NSF35FunctionKey: str # F35 function key
# Arrow keys
NSUpArrowFunctionKey: str # Up arrow key
NSDownArrowFunctionKey: str # Down arrow key
NSLeftArrowFunctionKey: str # Left arrow key
NSRightArrowFunctionKey: str # Right arrow key
# Special function keys
NSInsertFunctionKey: str # Insert key
NSDeleteFunctionKey: str # Delete function key
NSHomeFunctionKey: str # Home key
NSBeginFunctionKey: str # Begin key
NSEndFunctionKey: str # End key
NSPageUpFunctionKey: str # Page Up key
NSPageDownFunctionKey: str # Page Down key
NSPrintScreenFunctionKey: str # Print Screen key
NSScrollLockFunctionKey: str # Scroll Lock key
NSPauseFunctionKey: str # Pause key
NSSysReqFunctionKey: str # System Request key
NSBreakFunctionKey: str # Break key
NSResetFunctionKey: str # Reset key
NSStopFunctionKey: str # Stop key
NSMenuFunctionKey: str # Menu key
NSUserFunctionKey: str # User function key
NSSystemFunctionKey: str # System function key
NSPrintFunctionKey: str # Print function key
NSClearLineFunctionKey: str # Clear Line key
NSClearDisplayFunctionKey: str # Clear Display key
NSInsertLineFunctionKey: str # Insert Line key
NSDeleteLineFunctionKey: str # Delete Line key
NSInsertCharFunctionKey: str # Insert Character key
NSDeleteCharFunctionKey: str # Delete Character key
NSPrevFunctionKey: str # Previous key
NSNextFunctionKey: str # Next key
NSSelectFunctionKey: str # Select key
NSExecuteFunctionKey: str # Execute key
NSUndoFunctionKey: str # Undo key
NSRedoFunctionKey: str # Redo key
NSFindFunctionKey: str # Find key
NSHelpFunctionKey: str # Help key
NSModeSwitchFunctionKey: str # Mode Switch keyPython-friendly enhancements to NSFontDescriptor providing dictionary-like access to font attributes.
# NSFontDescriptor enhancements (automatically available on NSFontDescriptor instances)
def __getitem__(self, key):
"""
Gets font attribute value for key using dictionary-style access.
Args:
key: Font attribute key (NSFontAttributeName constants)
Returns:
Font attribute value
Raises:
KeyError: If attribute key not found
"""
def get(self, key, default=None):
"""
Gets font attribute value with optional default.
Args:
key: Font attribute key
default: Value to return if key not found
Returns:
Font attribute value or default
"""import AppKit
# Create views
button1 = AppKit.NSButton.alloc().init()
button2 = AppKit.NSButton.alloc().init()
text_field = AppKit.NSTextField.alloc().init()
# Create variable bindings dictionary for visual format language
views = AppKit.NSDictionaryOfVariableBindings("button1", "button2", "text_field")
# Use with Auto Layout visual format
constraints = AppKit.NSLayoutConstraint.constraintsWithVisualFormat_options_metrics_views_(
"H:|-[button1]-[button2]-|",
0,
None,
views
)import AppKit
# Access shared application instance
app = AppKit.NSApp # Equivalent to NSApplication.sharedApplication()
# Terminate application
app.terminate_(None)
# Set application delegate
app.setDelegate_(my_app_delegate)
# Handle application activation
app.activateIgnoringOtherApps_(True)import AppKit
def keyDown_(self, event):
"""Handle key down events in a custom view."""
key_char = event.characters()
if key_char == AppKit.NSEnterCharacter:
self.handleEnterKey()
elif key_char == AppKit.NSBackspaceCharacter:
self.handleBackspaceKey()
elif key_char == AppKit.NSTabCharacter:
self.handleTabKey()
elif key_char in [AppKit.NSUpArrowFunctionKey, AppKit.NSDownArrowFunctionKey]:
self.handleArrowKeys(key_char)
elif key_char in [AppKit.NSF1FunctionKey, AppKit.NSF2FunctionKey]:
self.handleFunctionKeys(key_char)
def handleSpecialKeys(self, event):
"""Handle special function keys."""
key_char = event.characters()
function_keys = {
AppKit.NSF1FunctionKey: self.showHelp,
AppKit.NSF2FunctionKey: self.renameItem,
AppKit.NSF5FunctionKey: self.refreshView,
AppKit.NSF11FunctionKey: self.toggleFullScreen,
}
if key_char in function_keys:
function_keys[key_char]()import AppKit
# Create font descriptor
font_descriptor = AppKit.NSFontDescriptor.fontDescriptorWithName_size_("Helvetica", 12)
# Use dictionary-like access to font attributes
family_name = font_descriptor[AppKit.NSFontFamilyAttribute]
font_size = font_descriptor.get(AppKit.NSFontSizeAttribute, 12.0)
# Get font traits
traits = font_descriptor.get(AppKit.NSFontTraitsAttribute, {})
if traits:
weight = traits.get(AppKit.NSFontWeightTrait, 0.0)
slant = traits.get(AppKit.NSFontSlantTrait, 0.0)import AppKit
import Foundation
# Create application window
window = AppKit.NSWindow.alloc().initWithContentRect_styleMask_backing_defer_(
Foundation.NSMakeRect(100, 100, 600, 400),
AppKit.NSWindowStyleMaskTitled | AppKit.NSWindowStyleMaskClosable | AppKit.NSWindowStyleMaskResizable,
AppKit.NSBackingStoreBuffered,
False
)
# Configure window
window.setTitle_("My Application")
window.center()
window.makeKeyAndOrderFront_(None)
# Access application instance
AppKit.NSApp.activateIgnoringOtherApps_(True)import AppKit
import Foundation
# Create button with character constant for key equivalent
button = AppKit.NSButton.alloc().initWithFrame_(Foundation.NSMakeRect(20, 20, 100, 30))
button.setTitle_("OK")
button.setKeyEquivalent_(AppKit.NSEnterCharacter) # Enter key activates button
button.setTarget_(self)
button.setAction_("okButtonPressed:")
# Create text field
text_field = AppKit.NSTextField.alloc().initWithFrame_(Foundation.NSMakeRect(20, 60, 200, 22))
text_field.setStringValue_("Enter text here")
# Add to window content view
content_view = window.contentView()
content_view.addSubview_(button)
content_view.addSubview_(text_field)import AppKit
class CustomView(AppKit.NSView):
def acceptsFirstResponder(self):
return True
def keyDown_(self, event):
characters = event.characters()
# Handle different types of input
if characters == AppKit.NSDeleteCharacter:
self.deleteSelection()
elif characters == AppKit.NSBackspaceCharacter:
self.backspaceAction()
elif characters in [AppKit.NSUpArrowFunctionKey, AppKit.NSDownArrowFunctionKey,
AppKit.NSLeftArrowFunctionKey, AppKit.NSRightArrowFunctionKey]:
self.handleArrowKey(characters)
elif characters.startswith(AppKit.NSF1FunctionKey[:1]): # Function key range
self.handleFunctionKey(characters)
else:
super(CustomView, self).keyDown_(event)
def handleArrowKey(self, arrow_char):
direction_map = {
AppKit.NSUpArrowFunctionKey: "up",
AppKit.NSDownArrowFunctionKey: "down",
AppKit.NSLeftArrowFunctionKey: "left",
AppKit.NSRightArrowFunctionKey: "right"
}
self.moveSelection(direction_map[arrow_char])AppKit provides comprehensive GUI capabilities including:
All AppKit classes and constants are available through dynamic attribute access:
import AppKit
# Access any AppKit class
window_class = AppKit.NSWindow
button_class = AppKit.NSButton
color_class = AppKit.NSColor
# Access constants
red_color = AppKit.NSColor.redColor()
app_kit_version = AppKit.NSAppKitVersionNumberInstall with Tessl CLI
npx tessl i tessl/pypi-pyobjc-framework-cocoa