¿Cómo puedo crear un elemento de la barra de estado con Cocoa y Python (PyObjC)?

StackOverflow https://stackoverflow.com/questions/141432

  •  02-07-2019
  •  | 
  •  

Pregunta

He creado un nuevo proyecto en XCode y tengo lo siguiente en mi archivo AppDelegate.py:

from Foundation import *
from AppKit import *

class MyApplicationAppDelegate(NSObject):
    def applicationDidFinishLaunching_(self, sender):
        NSLog("Application did finish launching.")

        statusItem = NSStatusBar.systemStatusBar().statusItemWithLength_(NSVariableStatusItemLength)
        statusItem.setTitle_(u"12%")
        statusItem.setHighlightMode_(TRUE)
        statusItem.setEnabled_(TRUE)

Sin embargo, cuando ejecuto la aplicación, no aparece ningún elemento de la barra de estado. Todos los demás códigos en main.py y main.m son predeterminados.

¿Fue útil?

Solución

Tuve que hacer esto para que funcione:

  1. Abre MainMenu.xib. Asegúrese de que la clase del delegado de la aplicación sea MyApplicationAppDelegate . No estoy seguro de si tendrás que hacer esto, pero lo hice. Estaba mal y, por lo tanto, el delegado de la aplicación nunca fue llamado en primer lugar.

  2. Agrega statusItem.retain () porque se publica automáticamente de inmediato.

Otros consejos

El uso anterior de .retain () es necesario porque el statusItem se está destruyendo al regresar del método applicationDidFinishLaunching (). Enlazar esa variable como un campo en instancias de MyApplicationAppDelegate usando self.statusItem en su lugar.

Aquí hay un ejemplo modificado que no requiere un .xib / etc ...

from Foundation import *
from AppKit import *
from PyObjCTools import AppHelper

start_time = NSDate.date()


class MyApplicationAppDelegate(NSObject):

    state = 'idle'

    def applicationDidFinishLaunching_(self, sender):
        NSLog("Application did finish launching.")

        self.statusItem = NSStatusBar.systemStatusBar().statusItemWithLength_(NSVariableStatusItemLength)
        self.statusItem.setTitle_(u"Hello World")
        self.statusItem.setHighlightMode_(TRUE)
        self.statusItem.setEnabled_(TRUE)

        # Get the timer going
        self.timer = NSTimer.alloc().initWithFireDate_interval_target_selector_userInfo_repeats_(start_time, 5.0, self, 'tick:', None, True)
        NSRunLoop.currentRunLoop().addTimer_forMode_(self.timer, NSDefaultRunLoopMode)
        self.timer.fire()

    def sync_(self, notification):
        print "sync"

    def tick_(self, notification):
        print self.state


if __name__ == "__main__":
    app = NSApplication.sharedApplication()
    delegate = MyApplicationAppDelegate.alloc().init()
    app.setDelegate_(delegate)
    AppHelper.runEventLoop()
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top