简体   繁体   English

NSMenuItem + Python +动态变量

[英]NSMenuItem + Python + Dynamic Variables

I'm trying to get a dynamic label for a menu item in this. 我正在尝试为此菜单项获取动态标签。 I've written the entire app in Python but honestly with how much NSMenuItem looks, I might as well rewrite it in Objc... 我已经用Python编写了整个应用程序,但是老实说,NSMenuItem看起来是多少,我不妨用Objc重写它...

import objc
from Foundation import *
from AppKit import *
from PyObjCTools import AppHelper

class MyApp(NSApplication):

    def finishLaunching(self):
        # Make statusbar item
        statusbar = NSStatusBar.systemStatusBar()
        self.statusitem = statusbar.statusItemWithLength_(NSVariableStatusItemLength)
        self.icon = NSImage.alloc().initByReferencingFile_('icon.png')
        self.icon.setScalesWhenResized_(True)
        self.icon.setSize_((20, 20))
        self.statusitem.setImage_(self.icon)

        #make the menu
        self.menubarMenu = NSMenu.alloc().init()

        self.menuItem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Click Me', 'clicked:', '')
        self.menubarMenu.addItem_(self.menuItem)

        self.quit = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Quit', 'terminate:', '')
        self.menubarMenu.addItem_(self.quit)

        #add menu to statusitem
        self.statusitem.setMenu_(self.menubarMenu)
        self.statusitem.setToolTip_('My App')

    def clicked_(self, notification):
        NSLog('clicked!')

if __name__ == "__main__":
    app = MyApp.sharedApplication()
    AppHelper.runEventLoop()

Did you try setTitle_ ? 您尝试过setTitle_吗?

def clicked_(self, notification):
    self.menuItem.setTitle_("Clicked!")

or with a timer: 或使用计时器:

def finishLaunching(self):
    # ...

    self.timer = NSTimer.alloc().initWithFireDate_interval_target_selector_userInfo_repeats_(NSDate.date(), 1.0, self, 'tick:', None, True)
    NSRunLoop.currentRunLoop().addTimer_forMode_(self.timer, NSDefaultRunLoopMode)
    self.timer.fire()


def tick_(self, arg):
    self.menuItem.setTitle_("Tick %d!" % int(time.time()))

For live updates you probably need JGMenuWindow ( SO: How to update NSMenu while it's open? ) 对于实时更新,您可能需要JGMenuWindow (因此:如何在NSMenu打开时更新它?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM