【问题标题】:How can I create a status bar item with Cocoa and Python (PyObjC)?如何使用 Cocoa 和 Python (PyObjC) 创建状态栏项目?
【发布时间】:2008-09-26 19:29:48
【问题描述】:

我在 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 中的所有其他代码都是默认的。

【问题讨论】:

    标签: python cocoa pyobjc


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      我必须这样做才能使它工作:

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

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

      【讨论】:

      • 是 statusItem.retain() 做到了。谢谢!
      • 很有趣,因为 PyObjC 文档说根本不需要进行手动内存管理。什么时候发布 statusItem?
      猜你喜欢
      • 1970-01-01
      • 2013-08-11
      • 2011-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-24
      • 1970-01-01
      • 2014-09-24
      相关资源
      最近更新 更多