macos 如何在 Python 中为 OSX 制作菜单栏(系统托盘)应用程序?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8544853/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to make an menu bar (system tray) app for OSX in Python?
提问by freeall
After having spent quite some time looking at ways to an app for the menu bar we're close to admit defeat.
在花了相当多的时间寻找菜单栏应用程序的方法之后,我们已经接近承认失败了。
We are basically just looking for an example/pointer on how to create an app that will put itself in the menu bar (the small icons next to the clock), and have a menu. Nothing fancy at all.
我们基本上只是在寻找一个关于如何创建一个应用程序的示例/指针,该应用程序将自己放在菜单栏(时钟旁边的小图标)中,并有一个菜单。一点都不花哨。
It feels like something that should be very easy to do, but we haven't been able to find an example that works.
感觉应该很容易做的事情,但我们一直没能找到一个有效的例子。
Maybe it's not possible with Python? Does anyone know how others do it?
也许用 Python 是不可能的?有谁知道别人是怎么做的?
回答by Jared
An option would be to use rumps
which provides a level of abstraction on top of PyObjC. I wrote it specifically for quickly generating these types of simple status bar apps.
一种选择是使用rumps
它在 PyObjC 之上提供抽象级别。我专门为快速生成这些类型的简单状态栏应用程序而编写的。
I hope that this could help a few people out there looking for a simple, semantic solution!
我希望这可以帮助一些寻找简单语义解决方案的人!
A short example snippet follows. Decorators are used for registering functions as callbacks for click events and timers. There is also support for 10.8 notifications.
下面是一个简短的示例片段。装饰器用于将函数注册为单击事件和计时器的回调。还支持 10.8 通知。
import rumps
class AwesomeStatusBarApp(rumps.App):
def __init__(self):
super(AwesomeStatusBarApp, self).__init__("Awesome App")
self.menu = ["Preferences", "Silly button", "Say hi"]
@rumps.clicked("Preferences")
def prefs(self, _):
rumps.alert("jk! no preferences available!")
@rumps.clicked("Silly button")
def onoff(self, sender):
sender.state = not sender.state
@rumps.clicked("Say hi")
def sayhi(self, _):
rumps.notification("Awesome title", "amazing subtitle", "hi!!1")
if __name__ == "__main__":
AwesomeStatusBarApp().run()
回答by maranas
wxPython won't be able to add a taskbar item. You can do this by instead using PyObjC like so:
wxPython 将无法添加任务栏项目。您可以通过使用 PyObjC 来做到这一点,如下所示:
from AppKit import NSStatusBar
status_item = NSStatusBar.systemStatusBar().statusItemWithLength_(-1) #NSVariableStatusItemLength
status_item.setImage_(<NSImage instance to status icon>)
Just refer to the NSStatusItem class reference to do stuff to the item, e.g. add a menu, change the highlight image, etc.
只需参考 NSStatusItem 类引用即可对项目进行操作,例如添加菜单、更改高亮图像等。
回答by Generic Ratzlaugh
Actually, you canuse wxPython. Refer to my related answer here: how to set a menubar icon on mac osx using wx
实际上,您可以使用 wxPython。参考我的相关回答:how to set a menubar icon on mac osx using wx