2015-02-11 42 views
2

我想在pygobject的通知中顯示按鈕。這個按鈕應該在點擊時調用一個回調函數,但它不會,我不明白爲什麼。未使用pygobject通知操作調用回叫

這裏是我的代碼:

from gi.repository import Notify, Gtk 

class Test: 
    def __init__(self): 
     Notify.init('example') 
     self.notif() 

     Gtk.main() 

    def notif(self): 
     notif = Notify.Notification.new('Title', 'something','dialog-information') 

     notif.add_action('display', 'Button', self.callback, None) 
     notif.show() 

    def callback(self, notif_object, action_name, users_data): 
     print("Work!") 
     Gtk.main_quit() 

Test() 

當我點擊按鈕「按鈕」,沒有任何反應和回調不叫。 問題是什麼?

經過一番嘗試,我發現當我把Gtk.main()緊接在notif.show()後面時,回調工作。但是我不能使用這個解決方案,因爲它暗示我以後不能再顯示其他通知。

回答

0

UPDATE

看來你並不需要調用

Gdk.threads_init() 

不記得我測試過這個情況,但敢發誓這是有人對我的差異。

更新例如:

import sys 

from gi.repository import Notify 
from gi.repository import Gtk 

if not Notify.init('Notification Test'): 
    print("ERROR: Could not init Notify.") 
    sys.exit(1) 

notification = Notify.Notification.new(
    "Notification Title", 
    "Message...") 

notification.set_urgency(Notify.Urgency.NORMAL) 
def actionCallback(notification, action, user_data = None): 
    print("Callback called:"+action) 
    Gtk.main_quit() 

notification.add_action("test-action", "Test Action", actionCallback) 

if not notification.show(): 
    print("ERROR: Could not show notification.") 
    sys.exit(2) 

Gtk.main() 
+0

PyGObject 3.10.2+中實際不需要'Gdk.threads_init()'。你的例子是有效的,因爲當你調用'Gtk.main()'時你仍然持有'notification'的引用,並且不能解決OP所具有的問題。 – Fenikso 2015-09-29 08:40:10

1

您需首先引用您的通知對象,直到調用回調:

from gi.repository import Gtk, Notify 


class Window(Gtk.Window): 
    def __init__(self, *args, **kwargs): 
     super().__init__(*args, **kwargs) 
     Notify.init('Test') 
     self.notification = None 

     self.set_border_width(5) 

     self.button = Gtk.Button('Test') 

     self.box = Gtk.Box() 
     self.box.pack_start(self.button, True, True, 0) 
     self.add(self.box) 

     self.button.connect('clicked', self.on_button) 
     self.connect('delete-event', Gtk.main_quit) 
     self.show_all() 

    def on_button(self, button): 
     if self.notification: 
      self.notification.close() 
     self.notification = Notify.Notification.new('Test') 
     self.notification.add_action('clicked', 'Action', self.callback) 
     self.notification.show() 

    def callback(self, notification, action_name): 
     print(action_name) 

win = Window() 
Gtk.main() 

如果你需要證明你越需要相同的通知通知對象的列表。

對於無窗口示例,請參閱此answer