Python 未使用pygobject通知操作调用回调
我想在pygobject的通知中显示一个按钮。这个按钮应该在单击时调用回调,但它没有,我不明白为什么 这是我的密码:Python 未使用pygobject通知操作调用回调,python,notifications,pygobject,Python,Notifications,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
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()
当我点击按钮“button”时,不会发生任何事情,也不会调用回调。
有什么问题
经过一些尝试,我发现当我将
Gtk.main()
紧跟在notif.show()
之后时,回调就起作用了。但我无法使用此解决方案,因为它意味着我以后无法显示其他通知。更新
看来你不需要打电话了
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()
在调用回调之前,您需要保留对通知对象的引用:
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()
如果需要显示更多相同的通知,则需要通知对象列表
有关无窗口示例,请参见。Gdk.threads\u init()
在PyGObject 3.10.2+中实际上不需要。您的示例之所以有效,是因为在调用Gtk.main()
时,您仍然持有对notification
的引用,并且没有解决OP遇到的问题。