如何使用Cocoa和Python(PyObjC)创建状态栏项目?

9
我已在XCode中创建了一个全新的项目,并在我的AppDelegate.py文件中有以下内容:
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中的所有其他代码都是默认值。
2个回答

6

由于statusItem在applicationDidFinishLaunching()方法返回后被销毁,因此需要使用.retain()来保留其状态。将该变量绑定为MyApplicationAppDelegate实例的字段,可使用self.statusItem。

以下是一个修改后的示例,不需要.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()

5

我必须这样做才能让它正常工作:

  1. 打开MainMenu.xib。确保应用程序委托的类是MyApplicationAppDelegate。我不确定你是否需要这样做,但我做了。因为我的方法是错误的,所以应用程序委托根本没有被调用。

  2. 添加statusItem.retain(),因为它会立即被自动释放。


1
正是 statusItem.retain() 让它实现了。谢谢! - davidmytton
有意思,因为 PyObjC 文档说根本不需要手动进行内存管理。你什么时候释放 statusItem? - Yi.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接