Bitte warten

GTK 4: Menü-Widgets

Menüs definieren

► GTK Dokumentation: Gtk.Builder
► GIO Dokumentation: MenuModel

In GTK 4 werden Menüs im XML-Format definiert und entweder aus einer entsprechenden Datei gelesen oder als String eingebunden. Die XML-Deklaration enthält folgende Elemente:

<interface>
Wurzelelement. Keine Attribute. Enthält <menu>.

<menu id='menu_id'>
Container für das gesamte Menü. Enthält <submenu>.

<submenu>
Untermenü. Keine Attribute. Enthält <attribute> und <section>.

<attribute name='label' translatable='yes'>
Bezeichner des Untermenüs.

<section>
Container für zusammengehörige Items. Keine Attribute. Enthält <item>.

<item>
Menüoption. Keine Attribute. Enthält <attribute>.

<attribute>
Eigenschaften der Menüoption. Attribute:
name='label' – Bezeichner der Menüoption
name='action' – Aktion. Methode.
name='target' – Wert für Aktion.
name='accel' – Keybinding.

Code kopieren
<?xml version="1.0" encoding="UTF-8"?>
<interface>
    <menu id="app-menu">
        <submenu>
            <attribute name="label" translatable="yes">Datei</attribute>
            <section>
                <item>
                    <attribute name="label" translatable="yes">Öffnen</attribute>
                    <attribute name="action">win.open_file</attribute>
                    <attribute name="target">Option: Datei öffnen</attribute>
                    <attribute name="accel">&lt;Primary$gt;o</attribute>
                </item>
            </section>
        </submenu>
    </menu>
</interface>

Moderne Variante: Gtk.PopoverMenu

► PyGObject Tutorial: Menu Popover
► GIO Dokumentation: Gio.SimpleAction

Möchte man zur Kopfleiste der Benutzeroberfläche einen Button hinzufügen, über den sich ein Menü aufklappen lässt, geht man folgendermaßen vor.

Man beachte das Attribut id="app-menu" des Elements <menu> in der XML-Deklaration, sowie das Builder-Objekt "app-menu" in Zeile 35.

Code kopieren
#!/usr/bin/python3
import gi
gi.require_version("Gtk", "4.0")
from gi.repository import GLib, Gio, Gtk

MENU_XML = """
<?xml version="1.0" encoding="UTF-8"?>
<interface>
    <menu id="app-menu">
        <submenu>
            <attribute name="label" translatable="yes">Datei</attribute>
            <section>
                <item>
                    <attribute name="label" translatable="yes">Öffnen</attribute>
                    <attribute name="action">win.open_file</attribute>
                    <attribute name="target">Option: Datei öffnen</attribute>
                    <attribute name="accel">&lt;Primary$gt;o</attribute>
                </item>
            </section>
        </submenu>
    </menu>
</interface>
"""

class MyWindow(Gtk.ApplicationWindow):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs, title="GTK 4 Beispiel")
        self.set_icon_name("python")
        self.set_default_size(300, 300)

        headerbar = Gtk.HeaderBar()
        self.set_titlebar(headerbar)

        builder = Gtk.Builder.new_from_string(MENU_XML, -1)
        menu_model = builder.get_object("app-menu")

        button = Gtk.MenuButton(menu_model=menu_model)
        headerbar.pack_end(button)

        menu_action01 = Gio.SimpleAction.new(
            "open_file",  # name
            GLib.Variant.new_string("dummy").get_type()  # parameter_type
        )
        menu_action01.connect("activate", self.on_open_file)
        self.add_action(menu_action01)

    def on_open_file(self, action, value):
        print(value)

def on_activate(app):
    win = MyWindow(application=app)
    win.present()

app = Gtk.Application(application_id="com.example.MyApp")
app.connect("activate", on_activate)
app.run(None)

Klassische Variante: Menüleiste

► PyGObject Tutorial: Menus

Möchte man zur Benutzeroberfläche eine Menüleiste mit individuellen Rubriken hinzufügen, bei der die einzelnen Menüoptionen in Untermenüs angeordnet sind, geht man folgendermaßen vor.

Man beachte das Attribut id="menubar" des Elements <menu> in der XML-Deklaration, sowie das Builder-Objekt "menubar" in Zeile 32.

Code kopieren
#!/usr/bin/python3
import gi
gi.require_version("Gtk", "4.0")
from gi.repository import GLib, Gio, Gtk

MENU_XML = """
<?xml version="1.0" encoding="UTF-8"?>
<interface>
    <menu id="menubar">
        <submenu>
            <attribute name="label" translatable="yes">Datei</attribute>
            <section>
                <item>
                    <attribute name="label" translatable="yes">Öffnen</attribute>
                    <attribute name="action">win.open_file</attribute>
                    <attribute name="target">Option: Datei öffnen</attribute>
                    <attribute name="accel">&lt;Primary$gt;o</attribute>
                </item>
            </section>
        </submenu>
    </menu>
</interface>
"""

class MyWindow(Gtk.ApplicationWindow):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs, title="GTK 4 Beispiel")
        self.set_icon_name("python")
        self.set_default_size(300, 300)

        builder = Gtk.Builder.new_from_string(MENU_XML, -1)
        app.set_menubar(builder.get_object("menubar"))
        self.set_show_menubar(True)

        menu_action01 = Gio.SimpleAction.new(
            "open_file",  # name
            GLib.Variant.new_string("dummy").get_type()  # parameter_type
        )
        menu_action01.connect("activate", self.on_open_file)
        self.add_action(menu_action01)

    def on_open_file(self, action, value):
        print(value)

def on_activate(app):
    win = MyWindow(application=app)
    win.present()

app = Gtk.Application(application_id="com.example.MyApp")
app.connect("activate", on_activate)
app.run(None)