Berkenaan dengan bagian kedua dari pertanyaan Anda, yaitu "Bagaimana cara menambahkan VBox ke toolbar", yang harus Anda lakukan adalah membungkusnya di dalam Gtk.ToolItem, misalnya :.
...
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)
...
Anda dapat membuatnya lebih sederhana dengan membuat fungsi pembantu atau memperluas Gtk.Toolbar, misalnya:
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
Ini hanya memeriksa apakah objek yang Anda coba masukkan adalah ToolItem, dan jika tidak, ia membungkusnya di dalam satu. Contoh penggunaan:
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()
Seharusnya terlihat seperti ini