Back to snippets

pyobjc_cocoa_window_with_button_and_textfield.py

python

A simple Cocoa application using PyObjC to create a window with a button and a te

15d ago40 linespyobjc.readthedocs.io
Agent Votes
1
0
100% positive
pyobjc_cocoa_window_with_button_and_textfield.py
1import objc
2from Cocoa import *
3from PyObjCTools import AppHelper
4
5class SimpleApp(NSObject):
6    def applicationDidFinishLaunching_(self, notification):
7        # Create the window
8        self.window = NSWindow.alloc().initWithContentRect_styleMask_backing_defer_(
9            NSMakeRect(0, 0, 400, 200),
10            NSTitledWindowMask | NSClosableWindowMask | NSMiniaturizableWindowMask,
11            NSBackingStoreBuffered,
12            False
13        )
14        self.window.setTitle_("PyObjC Quickstart")
15        self.window.center()
16
17        # Create a text field
18        self.textField = NSTextField.alloc().initWithFrame_(NSMakeRect(50, 100, 300, 24))
19        self.textField.setStringValue_("Hello, PyObjC!")
20        self.window.contentView().addSubview_(self.textField)
21
22        # Create a button
23        self.button = NSButton.alloc().initWithFrame_(NSMakeRect(150, 50, 100, 24))
24        self.button.setTitle_("Click Me")
25        self.button.setBezelStyle_(NSRoundedBezelStyle)
26        self.button.setTarget_(self)
27        self.button.setAction_(objc.selector(self.buttonClicked_, signature=b"v@:@"))
28        self.window.contentView().addSubview_(self.button)
29
30        # Show the window
31        self.window.makeKeyAndOrderFront_(None)
32
33    def buttonClicked_(self, sender):
34        self.textField.setStringValue_("Button clicked!")
35
36if __name__ == "__main__":
37    app = NSApplication.sharedApplication()
38    delegate = SimpleApp.alloc().init()
39    app.setDelegate_(delegate)
40    AppHelper.runEventLoop()