Menüs¶
Bemerkung
Gtk.UIManager
, Gtk.Action
, and Gtk.ActionGroup
have been deprecated since GTK+ version 3.10 and should not be used in
newly-written code. Use the Anwendung framework instead.
GTK+ comes with two different types of menus, Gtk.MenuBar
and
Gtk.Toolbar
. Gtk.MenuBar
is a standard menu bar which contains
one or more Gtk.MenuItem
instances or one of its subclasses.
Gtk.Toolbar
widgets are used for quick accessibility to commonly used
functions of an application. Examples include creating a new document, printing
a page or undoing an operation. It contains one or more instances of
Gtk.ToolItem
or one of its subclasses.
Befehl¶
Although, there are specific APIs to create menus and toolbars, you should
use Gtk.UIManager
and create Gtk.Action
instances.
Actions are organised into groups. A Gtk.ActionGroup
is essentially a
map from names to Gtk.Action
objects.
All actions that would make sense to use in a particular context should be in a
single group. Multiple action groups may be used for a particular user interface.
In fact, it is expected that most non-trivial applications will make use of
multiple groups. For example, in an application that can edit multiple documents,
one group holding global actions (e.g. quit, about, new), and one group per
document holding actions that act on that document (eg. save, cut/copy/paste, etc).
Each window’s menus would be constructed from a combination of two action groups.
Different classes representing different types of actions exist:
Gtk.Action
: An action which can be triggered by a menu or toolbar itemGtk.ToggleAction
: An action which can be toggled between two statesGtk.RadioAction
: An action of which only one in a group can be activeGtk.RecentAction
: An action of which represents a list of recently used files
Actions represent operations that the user can be perform, along with some information how it should be presented in the interface, including its name (not for display), its label (for display), an accelerator, whether a label indicates a tooltip as well as the callback that is called when the action gets activated.
You can create actions by either calling one of the constructors directly and
adding them to a Gtk.ActionGroup
by calling
Gtk.ActionGroup.add_action()
or Gtk.ActionGroup.add_action_with_accel()
,
or by calling one of the convenience functions:
Note that you must specify actions for sub menus as well as menu items.
UI Manager¶
Gtk.UIManager
provides an easy way of creating menus and toolbars using
an XML-like description.
First of all, you should add the Gtk.ActionGroup
to the UI Manager with
Gtk.UIManager.insert_action_group()
. At this point is also a good idea to
tell the parent window to respond to the specified keyboard shortcuts, by using
Gtk.UIManager.get_accel_group()
and Gtk.Window.add_accel_group()
.
Then, you can define the actual visible layout of the menus and toolbars, and add the UI layout. This „ui string“ uses an XML format, in which you should mention the names of the actions that you have already created. Remember that these names are just the identifiers that we used when creating the actions. They are not the text that the user will see in the menus and toolbars. We provided those human-readable names when we created the actions.
Finally, you retrieve the root widget with Gtk.UIManager.get_widget()
and add the widget to a container such as Gtk.Box
.
Beispiel¶
1import gi
2
3gi.require_version("Gtk", "3.0")
4from gi.repository import Gtk, Gdk
5
6UI_INFO = """
7<ui>
8 <menubar name='MenuBar'>
9 <menu action='FileMenu'>
10 <menu action='FileNew'>
11 <menuitem action='FileNewStandard' />
12 <menuitem action='FileNewFoo' />
13 <menuitem action='FileNewGoo' />
14 </menu>
15 <separator />
16 <menuitem action='FileQuit' />
17 </menu>
18 <menu action='EditMenu'>
19 <menuitem action='EditCopy' />
20 <menuitem action='EditPaste' />
21 <menuitem action='EditSomething' />
22 </menu>
23 <menu action='ChoicesMenu'>
24 <menuitem action='ChoiceOne'/>
25 <menuitem action='ChoiceTwo'/>
26 <separator />
27 <menuitem action='ChoiceThree'/>
28 </menu>
29 </menubar>
30 <toolbar name='ToolBar'>
31 <toolitem action='FileNewStandard' />
32 <toolitem action='FileQuit' />
33 </toolbar>
34 <popup name='PopupMenu'>
35 <menuitem action='EditCopy' />
36 <menuitem action='EditPaste' />
37 <menuitem action='EditSomething' />
38 </popup>
39</ui>
40"""
41
42
43class MenuExampleWindow(Gtk.Window):
44 def __init__(self):
45 Gtk.Window.__init__(self, title="Menu Example")
46
47 self.set_default_size(200, 200)
48
49 action_group = Gtk.ActionGroup(name="my_actions")
50
51 self.add_file_menu_actions(action_group)
52 self.add_edit_menu_actions(action_group)
53 self.add_choices_menu_actions(action_group)
54
55 uimanager = self.create_ui_manager()
56 uimanager.insert_action_group(action_group)
57
58 menubar = uimanager.get_widget("/MenuBar")
59
60 box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
61 box.pack_start(menubar, False, False, 0)
62
63 toolbar = uimanager.get_widget("/ToolBar")
64 box.pack_start(toolbar, False, False, 0)
65
66 eventbox = Gtk.EventBox()
67 eventbox.connect("button-press-event", self.on_button_press_event)
68 box.pack_start(eventbox, True, True, 0)
69
70 label = Gtk.Label(label="Right-click to see the popup menu.")
71 eventbox.add(label)
72
73 self.popup = uimanager.get_widget("/PopupMenu")
74
75 self.add(box)
76
77 def add_file_menu_actions(self, action_group):
78 action_filemenu = Gtk.Action(name="FileMenu", label="File")
79 action_group.add_action(action_filemenu)
80
81 action_filenewmenu = Gtk.Action(name="FileNew", stock_id=Gtk.STOCK_NEW)
82 action_group.add_action(action_filenewmenu)
83
84 action_new = Gtk.Action(
85 name="FileNewStandard",
86 label="_New",
87 tooltip="Create a new file",
88 stock_id=Gtk.STOCK_NEW,
89 )
90 action_new.connect("activate", self.on_menu_file_new_generic)
91 action_group.add_action_with_accel(action_new, None)
92
93 action_group.add_actions(
94 [
95 (
96 "FileNewFoo",
97 None,
98 "New Foo",
99 None,
100 "Create new foo",
101 self.on_menu_file_new_generic,
102 ),
103 (
104 "FileNewGoo",
105 None,
106 "_New Goo",
107 None,
108 "Create new goo",
109 self.on_menu_file_new_generic,
110 ),
111 ]
112 )
113
114 action_filequit = Gtk.Action(name="FileQuit", stock_id=Gtk.STOCK_QUIT)
115 action_filequit.connect("activate", self.on_menu_file_quit)
116 action_group.add_action(action_filequit)
117
118 def add_edit_menu_actions(self, action_group):
119 action_group.add_actions(
120 [
121 ("EditMenu", None, "Edit"),
122 ("EditCopy", Gtk.STOCK_COPY, None, None, None, self.on_menu_others),
123 ("EditPaste", Gtk.STOCK_PASTE, None, None, None, self.on_menu_others),
124 (
125 "EditSomething",
126 None,
127 "Something",
128 "<control><alt>S",
129 None,
130 self.on_menu_others,
131 ),
132 ]
133 )
134
135 def add_choices_menu_actions(self, action_group):
136 action_group.add_action(Gtk.Action(name="ChoicesMenu", label="Choices"))
137
138 action_group.add_radio_actions(
139 [
140 ("ChoiceOne", None, "One", None, None, 1),
141 ("ChoiceTwo", None, "Two", None, None, 2),
142 ],
143 1,
144 self.on_menu_choices_changed,
145 )
146
147 three = Gtk.ToggleAction(name="ChoiceThree", label="Three")
148 three.connect("toggled", self.on_menu_choices_toggled)
149 action_group.add_action(three)
150
151 def create_ui_manager(self):
152 uimanager = Gtk.UIManager()
153
154 # Throws exception if something went wrong
155 uimanager.add_ui_from_string(UI_INFO)
156
157 # Add the accelerator group to the toplevel window
158 accelgroup = uimanager.get_accel_group()
159 self.add_accel_group(accelgroup)
160 return uimanager
161
162 def on_menu_file_new_generic(self, widget):
163 print("A File|New menu item was selected.")
164
165 def on_menu_file_quit(self, widget):
166 Gtk.main_quit()
167
168 def on_menu_others(self, widget):
169 print("Menu item " + widget.get_name() + " was selected")
170
171 def on_menu_choices_changed(self, widget, current):
172 print(current.get_name() + " was selected.")
173
174 def on_menu_choices_toggled(self, widget):
175 if widget.get_active():
176 print(widget.get_name() + " activated")
177 else:
178 print(widget.get_name() + " deactivated")
179
180 def on_button_press_event(self, widget, event):
181 # Check if right mouse button was preseed
182 if event.type == Gdk.EventType.BUTTON_PRESS and event.button == 3:
183 self.popup.popup(None, None, None, None, event.button, event.time)
184 return True # event has been handled
185
186
187window = MenuExampleWindow()
188window.connect("destroy", Gtk.main_quit)
189window.show_all()
190Gtk.main()