2008-09-26 55 views
8

我创建XCode中一个全新的项目,并在我的AppDelegate.py文件中的以下内容:如何用Cocoa和Python(PyObjC)创建状态栏项目?

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) 

然而,当我启动应用程序没有状态栏项显示出来。 main.py和main.m中的所有其他代码都是默认的。

回答

5

我不得不这样做,使其工作:

  1. 打开MainMenu.xib。确保应用程序代理的类是MyApplicationAppDelegate。我不确定你是否必须这样做,但我确实。这是错误的,所以应用程序代表从来没有得到首先调用。

  2. 添加statusItem.retain(),因为它马上被自动释放。

+1

这是statusItem.retain(),它做到了。谢谢! – DavidM 2008-09-27 10:32:53

4

.retain()的上述用法是必需的,因为statusItem在从applicationDidFinishLaunching()方法返回时被销毁。改为使用self.statusItem将该变量作为MyApplicationAppDelegate实例中的字段绑定。

这里是一个修改的例子,不需要的.xib /等...

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()