objective-ccocoanswindownsimagepyobjc

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


I'm trying to add an image to an NSPanel, by calling the .addSubvew_(image) method in Python, but I keep getting [NSImage window]: unrecognized selector sent to instance 0x7fbb246a9e10. I'm not sure, whether the problem is an initialization problem of the image, or whether im adding the Subview incorrectly. But it seems to be the case that the initialization works just fine, since it doesn't give any errors when running alone. Here's the full code:

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

Solution

  • NSView’s addSubview: method adds a view - you need to create a view for the image. Using NSImageView and replacing your image statements would be something like:

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