Python program with Notification in Gnome Shell doesn't work

帅比萌擦擦* 提交于 2019-12-01 01:12:54

The GUI applications usually use three main components: widgets, event loop and callbacks. When you start that application, you create widgets, register callbacks and start event loop. Event loop is infinite loop which looks for events from widgets (such as 'clicked button') and fires corresponding callbacks.

Now, in your application you have another infinite loop, so these two will not play along. Instead, you should make use of the GLib.MainLoop().run() to fire events. You can use GLib.timeout_add_seconds to fire periodic events such as your every 10 seconds.

Second problem is that you need to hold reference to a notification which is supposed to call callbacks. The reason why it worked when you added GLib.MainLoop().run() after noti.show() is that reference to noti still exists, but it would not work if you would do changes as I have suggested earlier. If you are sure there is always going to be just one notification active, you can hold the reference to the last notification. Otherwise you would need a list and periodically purge it or something along the lines.

The following example should set you in the right direction:

from gi.repository import GLib, Notify


class App():
    def __init__(self):
        self.last_notification = None
        Notify.init('Test')
        self.check()

    def check(self):
        self.last_notification = Notify.Notification.new('Test')
        self.last_notification.add_action('clicked', 'Action', 
                                          self.notification_callback, None)
        self.last_notification.show()
        GLib.timeout_add_seconds(10, self.check)

    def notification_callback(self, notification, action_name, data):
        print(action_name)


app = App()
GLib.MainLoop().run()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!