【发布时间】:2018-04-22 10:26:36
【问题描述】:
没有关于如何在PyGObject 中使用Gtk.Builder 创建菜单栏的完整文档。
我不使用 Gtk.UIManager,因为它已被弃用。
下面的示例代码基于我使用Gtk.UIManager 的经验。
在示例中应该出现一个菜单栏,其中 Foo 作为顶部菜单组,具有可点击的项目 Bar。
#!/usr/bin/env python3
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
from gi.repository import Gio
class Window(Gtk.ApplicationWindow):
def __init__(self):
Gtk.Window.__init__(self)
self.set_default_size(200, 100)
#
self.interface_info = """
<interface>
<menu id='TheMenu'>
<section>
<attribute name='foo'>Foo</attribute>
<item>
<attribute name='bar'>Bar</attribute>
</item>
</section>
</menu>
</interface>
"""
builder = Gtk.Builder.new_from_string(self.interface_info, -1)
action_bar = Gio.SimpleAction.new('bar', None)
action_bar.connect('activate', self.on_menu)
self.add_action(action_bar)
menubar = builder.get_object('TheMenu')
# layout
self.layout = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
self.layout.pack_start(menubar, True, True, 0)
self.add(self.layout)
self.connect('destroy', Gtk.main_quit)
self.show_all()
def on_menu(self, widget):
print(widget)
if __name__ == '__main__':
win = Window()
Gtk.main()
当前的错误是
Traceback (most recent call last):
File "./_menubar.py", line 46, in <module>
win = Window()
File "./_menubar.py", line 36, in __init__
self.layout.pack_start(menubar, True, True, 0)
TypeError: argument child: Expected Gtk.Widget, but got gi.repository.Gio.Menu
我不确定
- 如何创建 XML 字符串。
- 如何获取菜单栏小部件。
- 如何为菜单项创建操作/点击处理程序。
当然这个问题可以扩展到工具栏,但我不会让它变得复杂。
顺便说一句:我不想使用Gtk.Application.set_menubar()。因为没有Gtk.Application.set_toolbar(),目前我认为拥有基于 Gtk 的应用程序对象没有任何优势。
编辑:我也试过这个变种(没有任何成功):
gio_menu = builder.get_object('TheMenu')
menubar = Gtk.Menubar.new_from_model(gio_menu)
【问题讨论】:
-
你可能想看看
amtk库,它旨在创建传统的 UI 而不使用已弃用的 GTK+ 组件:blogs.gnome.org/swilmet/2018/04/24/… -
@liberforce Amtk 看起来像 C?你能给出一个代码示例吗 - 文档中没有。用 PyGObject 创建一个菜单栏和一个工具栏就这么难,你需要另一个库吗?!
-
啊,对,也许它没有 python 绑定。不要忘记 GObject 和 GTK+ 也在 C 中,Amtk 只是另一个基于 GObject 的库。
-
也许toolbar created using Glade and GtkBuilder 的这个例子就是你要找的?
标签: python python-3.x gtk pygobject