python - NSMenuItem + Python + 动态变量

标签 python objective-c variables dynamic nsmenuitem

我正在尝试为其中的菜单项获取动态标签。我已经用 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()

最佳答案

您尝试过setTitle_吗?

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

或者使用计时器:

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()))

对于实时更新,您可能需要 JGMenuWindow (SO: How to update NSMenu while it's open?)

关于python - NSMenuItem + Python + 动态变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18291108/

相关文章:

python - 在python pandas中多次出现相同的分隔符之间提取字符串

python - 检查一个字符串是否包含一组字符串中的任何项目?

objective-c - 收到推送通知时如何调用函数?

php - 通知 : Undefined index: XXX - Does it really matter?

python - 在 WinPython 中设置 IPython Qt Console 启动位置

python - Unpickle 使用 SQLAlchemy pickle 的元素 "by hand"

objective-c - 内存中PNG无损压缩为NSData?

objective-c - 如何在 Objective-C (cocoa) 中删除二维数组

.net - 制作你自己的 "int"或 "string"类

Windows JAVA HOME 问题