Back to snippets
pyobjc_cocoa_macos_window_with_hello_world_label.py
pythonA minimal PyObjC application that creates a native macOS window w
Agent Votes
1
0
100% positive
pyobjc_cocoa_macos_window_with_hello_world_label.py
1from Cocoa import (
2 NSApplication,
3 NSApp,
4 NSWindow,
5 NSWindowStyleMaskTitled,
6 NSWindowStyleMaskClosable,
7 NSWindowStyleMaskResizable,
8 NSBackingStoreBuffered,
9 NSRect,
10 NSPoint,
11 NSSize,
12 NSTextField,
13)
14from PyObjCTools import AppHelper
15
16class AppDelegate:
17 def applicationDidFinishLaunching_(self, notification):
18 # Create a window
19 win = NSWindow.alloc().initWithContentRect_styleMask_backing_defer_(
20 NSRect(NSPoint(100, 100), NSSize(300, 200)),
21 NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | NSWindowStyleMaskResizable,
22 NSBackingStoreBuffered,
23 False,
24 )
25 win.setTitle_("PyObjC Quickstart")
26
27 # Create a text label
28 label = NSTextField.labelWithString_("Hello from PyObjC!")
29 label.setFrameOrigin_(NSPoint(80, 90))
30
31 win.contentView().addSubview_(label)
32 win.makeKeyAndOrderFront_(None)
33 print("Window should be visible now.")
34
35def main():
36 app = NSApplication.sharedApplication()
37 delegate = AppDelegate()
38 app.setDelegate_(delegate)
39 AppHelper.runEventLoop()
40
41if __name__ == "__main__":
42 main()