PencilKit Framework for PyObjC

12.1 · active · verified Tue Apr 14

pyobjc-framework-pencilkit provides Python wrappers for Apple's PencilKit framework on macOS. It is part of the PyObjC project, a bidirectional bridge enabling Python scripts to interact with Objective-C libraries, including macOS Cocoa frameworks. The current version is 12.1 and it maintains an active release cadence, typically aligning with macOS SDK updates and Python version support.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create a basic macOS application using PyObjC that displays a `PKCanvasView` and a `PKToolPicker` for drawing. It sets up a standard Cocoa application window and integrates PencilKit components, allowing for user interaction with an Apple Pencil or trackpad/mouse.

import AppKit
import Foundation
import PencilKit
from PyObjCTools import AppHelper

class PyPencilKitDelegate(AppKit.NSObject):
    def applicationDidFinishLaunching_(self, notification):
        # Create a window
        self.window = AppKit.NSWindow.alloc().initWithContentRect_styleMask_backing_defer_(
            Foundation.NSRect((100, 100), (600, 400)),
            AppKit.NSWindowStyleMaskTitled | AppKit.NSWindowStyleMaskClosable | AppKit.NSWindowStyleMaskResizable,
            AppKit.NSBackingStoreBuffered,
            False
        )
        self.window.setTitle_("PyObjC PencilKit Demo")
        self.window.setDelegate_(self)

        # Create a PKCanvasView
        self.canvasView = PencilKit.PKCanvasView.alloc().initWithFrame_(self.window.contentView().bounds())
        self.canvasView.setAutoresizingMask_(AppKit.NSViewWidthSizable | AppKit.NSViewHeightSizable)
        self.canvasView.setDrawingPolicy_(PencilKit.PKCanvasViewDrawingPolicyAnyInput) # Allow finger drawing

        # Create and configure a PKToolPicker
        self.toolPicker = PencilKit.PKToolPicker.alloc().init()
        self.toolPicker.setVisible_forFirstResponder_(True, self.canvasView) # Make visible for the canvas
        self.toolPicker.addObserver_(self.canvasView) # Canvas observes tool changes

        self.window.contentView().addSubview_(self.canvasView)
        self.window.makeKeyAndOrderFront_(None)

        # Make canvas first responder to receive drawing input
        self.window.makeFirstResponder_(self.canvasView)

    def applicationShouldTerminateAfterLastWindowClosed_(self, sender):
        return True

if __name__ == "__main__":
    app = AppKit.NSApplication.sharedApplication()
    delegate = PyPencilKitDelegate.alloc().init()
    app.setDelegate_(delegate)
    AppHelper.runEventLoop()

view raw JSON →