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

2024-10-01 09:39:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我在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)

但是,当我启动应用程序时,没有显示状态栏项。所有其他代码主.pymain.m是默认值。在


Tags: 文件项目frompyimporttruedefclass
2条回答

我必须这样做才能成功:

  1. 打开主菜单.xib. 确保应用程序委托的类是MyApplicationAppDelegate。我不确定你是否必须这么做,但我做了。这是错误的,所以应用程序代表一开始就没有被调用。

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

上面的.retain()用法是必需的,因为从ApplicationIDFinishLaunching()方法返回时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()

相关问题 更多 >