关于你的问题的第二部分,即“如何将VBox添加到工具栏”,你只需要将它包装在一个Gtk.ToolItem中即可。
...
self.toolbar = Gtk.Toolbar()
self.box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
tool_item = Gtk.ToolItem()
tool_item.add(self.box)
self.toolbar.insert(tool_item, 0)
...
你可以通过创建一个辅助函数或者扩展Gtk.Toolbar来简化它,例如:
custom_toolbar.py
from gi.repository import Gtk
class CustomToolbar(Gtk.Toolbar):
def __init__(self):
super(CustomToolbar, self).__init__()
''' Set toolbar style '''
context = self.get_style_context()
context.add_class(Gtk.STYLE_CLASS_PRIMARY_TOOLBAR)
def insert(self, item, pos):
''' If widget is not an instance of Gtk.ToolItem then wrap it inside one '''
if not isinstance(item, Gtk.ToolItem):
widget = Gtk.ToolItem()
widget.add(item)
item = widget
super(CustomToolbar, self).insert(item, pos)
return item
它只是检查您尝试插入的对象是否为ToolItem,如果不是,则将其包装在其中。使用示例:
main.py
#!/usr/bin/python
from gi.repository import Gtk
from custom_toolbar import CustomToolbar
class MySongPlayerWindow(Gtk.Window):
def __init__(self):
super(MySongPlayerWindow, self).__init__(title="My Song Player")
self.set_size_request(640, 480)
layout = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=6)
self.add(layout)
status_bar = Gtk.Statusbar()
layout.pack_end(status_bar, False, True, 0)
big_button = Gtk.Button(label="Play music")
layout.pack_end(big_button, True, True, 0)
''' Create a custom toolbar '''
toolbar = CustomToolbar()
toolbar.set_style(Gtk.ToolbarStyle.BOTH)
layout.pack_start(toolbar, False, True, 0)
''' Add some standard toolbar buttons '''
play_button = Gtk.ToggleToolButton(stock_id=Gtk.STOCK_MEDIA_PLAY)
toolbar.insert(play_button, -1)
stop_button = Gtk.ToolButton(stock_id=Gtk.STOCK_MEDIA_STOP)
toolbar.insert(stop_button, -1)
''' Create a vertical box '''
playback_info = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, margin_top=5, margin_bottom=5, margin_left=10, margin_right=10)
''' Add some children... '''
label_current_song = Gtk.Label(label="Artist - Song Name", margin_bottom=5)
playback_info.pack_start(label_current_song, True, True, 0)
playback_progress = Gtk.ProgressBar(fraction=0.6)
playback_info.pack_start(playback_progress, True, True, 0)
'''
Add the vertical box to the toolbar. Please note, that unlike Gtk.Toolbar.insert,
CustomToolbar.insert returns a ToolItem instance that we can manipulate
'''
playback_info_item = toolbar.insert(playback_info, -1)
playback_info_item.set_expand(True)
''' Add another custom item '''
search_entry = Gtk.Entry(text='Search')
search_item = toolbar.insert(search_entry, -1)
search_item.set_vexpand(False)
search_item.set_valign(Gtk.Align.CENTER)
win = MySongPlayerWindow()
win.connect("delete-event", Gtk.main_quit)
win.show_all()
Gtk.main()
它应该看起来像this
Gtk.get_major_version()
返回的是3
,但是我仍然得到的是旧的工具栏。这是在 Python2 和 Python3 中都执行了from gi.repository import Gtk
之后出现的情况。 - Stefano Palazzo