Wie kann ich eine Statusleiste Element mit Cocoa und Python (PyObjC) erstellen?
Frage
Ich habe ein neues Projekt in XCode erstellt und haben die folgenden in meiner AppDelegate.py-Datei:
from Foundation import *
from AppKit import *
class MyApplicationAppDelegate(NSObject):
def applicationDidFinishLaunching_(self, sender):
NSLog("Application did finish launching.")
statusItem = NSStatusBar.systemStatusBar().statusItemWithLength_(NSVariableStatusItemLength)
statusItem.setTitle_(u"12%")
statusItem.setHighlightMode_(TRUE)
statusItem.setEnabled_(TRUE)
Allerdings, wenn ich die Anwendung kein Statusleiste Element starten erscheint. Alle anderen Code in main.py und main.m ist Standard.
Lösung
Ich hatte dies zu tun, damit es funktioniert:
-
Öffnen MainMenu.xib. Achten Sie darauf, die Klasse der AppDelegate
MyApplicationAppDelegate
ist. Ich bin mir nicht sicher, ob Sie dies tun müssen, aber ich tat. Es war falsch, und so die AppDelegate nie an erster Stelle. genannt wurde
-
In
statusItem.retain()
weil es sofort Autoreleased wird.
Andere Tipps
Die obige Verwendung von .retain () erforderlich, da die statusItem aus dem applicationDidFinishLaunching () -Methode bei der Rückkehr zerstört. Binden Sie die Variable als ein Feld in Fällen von MyApplicationAppDelegate mit self.statusItem statt.
Hier ist ein modifiziertes Beispiel, das kein .xib erfordert / etc ...
from Foundation import *
from AppKit import *
from PyObjCTools import AppHelper
start_time = NSDate.date()
class MyApplicationAppDelegate(NSObject):
state = 'idle'
def applicationDidFinishLaunching_(self, sender):
NSLog("Application did finish launching.")
self.statusItem = NSStatusBar.systemStatusBar().statusItemWithLength_(NSVariableStatusItemLength)
self.statusItem.setTitle_(u"Hello World")
self.statusItem.setHighlightMode_(TRUE)
self.statusItem.setEnabled_(TRUE)
# Get the timer going
self.timer = NSTimer.alloc().initWithFireDate_interval_target_selector_userInfo_repeats_(start_time, 5.0, self, 'tick:', None, True)
NSRunLoop.currentRunLoop().addTimer_forMode_(self.timer, NSDefaultRunLoopMode)
self.timer.fire()
def sync_(self, notification):
print "sync"
def tick_(self, notification):
print self.state
if __name__ == "__main__":
app = NSApplication.sharedApplication()
delegate = MyApplicationAppDelegate.alloc().init()
app.setDelegate_(delegate)
AppHelper.runEventLoop()