Ali*_*cal 1 python gtk gobject
我试图在python/gtk3中创建一个弹出菜单.到目前为止,我尝试了以下代码:
from gi.repository import Gtk
def show_menu(self, *args):
menu = Gtk.Menu()
i1 = Gtk.MenuItem("Item 1")
menu.append(i1)
i2 = Gtk.MenuItem("Item 2")
menu.append(i2)
i2.show()
i1.show()
menu.popup(None, None, None, None, 0, Gtk.get_current_event_time())
print("Done")
window = Gtk.Window()
button = Gtk.Button("Create pop-up")
button.connect("clicked", show_menu)
window.add(button)
window.show_all()
Gtk.main()
Run Code Online (Sandbox Code Playgroud)
但弹出菜单没有出现?我究竟做错了什么?
由于menu是show_menu()函数中的局部变量,并且它没有被其他任何东西引用,它的引用计数降为0并且在函数结束时被销毁; 不幸的是,当你期待看到它时,这是正确的.
相反,menu在全局范围内创建它使得它menu不再是一个函数的本地,因此它不会在函数结束时被销毁.
from gi.repository import Gtk
def show_menu(self, *args):
i1 = Gtk.MenuItem("Item 1")
menu.append(i1)
i2 = Gtk.MenuItem("Item 2")
menu.append(i2)
menu.show_all()
menu.popup(None, None, None, None, 0, Gtk.get_current_event_time())
print("Done")
window = Gtk.Window()
button = Gtk.Button("Create pop-up")
menu = Gtk.Menu()
button.connect("clicked", show_menu)
window.connect('destroy', Gtk.main_quit)
window.add(button)
window.show_all()
Gtk.main()
Run Code Online (Sandbox Code Playgroud)