【问题标题】:NSUserNotificationCenter.defaultUserNotificationCenter() returns None in pythonNSUserNotificationCenter.defaultUserNotificationCenter() 在 python 中返回 None
【发布时间】:2013-04-07 22:19:51
【问题描述】:

我正在尝试通过 python 连接到 Mountain Lion 通知中心。我已经安装了 pyobjc 并按照herehere 的说明进行操作。另见:Working with Mountain Lion's Notification Center using PyObjC

这是我的代码:

import Foundation, objc
import AppKit
import sys

NSUserNotification = objc.lookUpClass('NSUserNotification')
NSUserNotificationCenter = objc.lookUpClass('NSUserNotificationCenter')

def notify(title, subtitle, info_text, delay=0, sound=False, userInfo={}):
    """ Python method to show a desktop notification on Mountain Lion. Where:
        title: Title of notification
        subtitle: Subtitle of notification
        info_text: Informative text of notification
        delay: Delay (in seconds) before showing the notification
        sound: Play the default notification sound
        userInfo: a dictionary that can be used to handle clicks in your
                  app's applicationDidFinishLaunching:aNotification method
    """
    notification = NSUserNotification.alloc().init()
    notification.setTitle_(title)
    notification.setSubtitle_(subtitle)
    notification.setInformativeText_(info_text)
    notification.setUserInfo_(userInfo)
    if sound:
        notification.setSoundName_("NSUserNotificationDefaultSoundName")
    notification.setDeliveryDate_(Foundation.NSDate.dateWithTimeInterval_sinceDate_(delay, Foundation.NSDate.date()))
    NSUserNotificationCenter.defaultUserNotificationCenter().scheduleNotification_(notification)

当我用参数调用通知函数时,我得到一个属性错误:

AttributeError: 'NoneType' object has no attribute 'scheduleNotification_'

我不明白为什么 NSUserNotificationCenter.defaultUserNotificationCenter() 返回一个 NoneType 对象。我无法在互联网或 SO 上查询有关此事的任何内容。

【问题讨论】:

  • 难道你不能只用三行代码 (import objc; NSUserNotificationCenter = objc.lookUpClass('NSUserNotificationCenter'); print NSUserNotificationCenter.defaultUserNotificationCenter()) 而不是整个函数来重现这个吗?
  • 啊!我想我可以!
  • FWIW,三行测试适用于我使用当前的 MacPorts python27 (@2.7.3_1) 和 py27-pyobjc (@2.5.1_0):它返回 _NSConcreteUserNotificationCenter 的实例.
  • 就此而言,三行测试也适用于我在 OS X 10.8.3 中使用当前 Apple 提供的系统 Python 2.7.2 (/usr/bin/python2.7)。 Apple 在其系统 Python 中发布了一个 PyObjC 版本。
  • 谢谢内德!我注意到它也适用于我使用默认的 python 2.7.2。但是,当我在 Enthought Python 的 64 位安装上使用 easy_install 安装 PyObjC 时,就会出现我上面提出的问题。目前我想我会在这个脚本中继续使用系统默认的python。

标签: python osx-mountain-lion nsnotificationcenter pyobjc nsusernotificationcenter


【解决方案1】:

因此,使用 Ned 的使用默认 python 的建议可以正常工作。当我在 32 位 enthought 发行版上安装 pyobjc 时,它也有效。在我看来,pyobjc 仅适用于 32 位 python 发行版(我无法确认这一点,但到目前为止似乎是这样)。

(注意:当我发布问题时,我已经在 64 位 enthought 发行版上安装了 pyobjc)。

【讨论】:

  • 但是,许多 Apple 框架将无法正常工作,除非二进制文件位于捆绑包(应用程序或插件)中。 Enthought 是安装一个框架还是只是一个普通的 unix 发行版?
  • 这适用于我使用 pyobjc 的本机安装和 64 位的自定义 python 安装。
猜你喜欢
  • 1970-01-01
  • 2018-08-14
  • 2018-03-29
  • 1970-01-01
  • 2022-12-12
  • 1970-01-01
  • 1970-01-01
  • 2022-12-25
  • 1970-01-01
相关资源
最近更新 更多