[NSImage window]:无法识别的选择器发送到 PyObjC 中的实例 0x7fbb246a9e10

[NSImage window]: unrecognized selector sent to instance 0x7fbb246a9e10 in PyObjC

我试图通过调用 Python 中的 .addSubvew_(image) 方法向 NSPanel 添加图像,但我一直收到 [NSImage window]: unrecognized selector sent to instance 0x7fbb246a9e10。我不确定,问题是图像的初始化问题,还是我添加的子视图不正确。但似乎初始化工作得很好,因为单独 运行 时它不会给出任何错误。 这是完整的代码:

from Cocoa import NSObject, NSApplication, NSApp, NSWindow, NSPanel, NSColor, NSImage, NSSound
from PyObjCTools import AppHelper

def main():
    NSApplication.sharedApplication()

    # we must keep a reference to the delegate object ourselves,
    # NSApp.setDelegate_() doesn't retain it. A local variable is
    # enough here.
    delegate = NSPanel.alloc().init()
    NSApp().setDelegate_(delegate)

    win = NSPanel.alloc()
    frame = ((875.0, 140.0), (180.0, 200.0))
    win.initWithContentRect_styleMask_backing_defer_(frame, 9395, 0, 5)
    win.setLevel_(0)  # floating window

    image1 = NSImage.alloc()
    image1.initWithContentsOfFile_('/Users/yassine/Teams.png')
    win.contentView().addSubview_(image1)
    win.display()
    win.orderFrontRegardless()  # but this one does
    AppHelper.runEventLoop()

if __name__ == "__main__":
    main()

NSView 的 addSubview: 方法添加了一个 view - 你需要为图像创建一个视图。使用 NSImageView 并替换您的图像语句将类似于:

#add NSImageView to the import
image = NSImage.alloc().initWithContentsOfFile_('/Users/yassine/Teams.png')
view = NSImageView.alloc().initWithFrame_(((10, 10), (150.0, 150.0)))
view.setImage_(image)
win.contentView().addSubview_(view)