CocoaとPython(PyObjC)でステータスバーアイテムを作成するにはどうすればよいですか?

StackOverflow https://stackoverflow.com/questions/141432

  •  02-07-2019
  •  | 
  •  

質問

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の他のすべてのコードはデフォルトです。

役に立ちましたか?

解決

これを機能させるにはこれを行わなければなりませんでした:

  1. MainMenu.xibを開きます。アプリデリゲートのクラスが MyApplicationAppDelegate であることを確認してください。あなたがこれをしなければならないかどうかはわかりませんが、私はしました。間違っていたため、そもそもアプリのデリゲートが呼び出されることはありませんでした。

  2. すぐに自動リリースされるため、 statusItem.retain()を追加します。

他のヒント

applicationDidFinishLaunching()メソッドから戻るとstatusItemが破棄されるため、上記の.retain()の使用が必要です。代わりに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()
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top