Une BarreDeMenu créée avec XML et GtkBuilder.
Pour créer une BarreDeMenu avec XML :
créez le fichier
Saisissez la ligne suivante en haut du fichier :
]]>
We want to create the interface which will contain our menubar and its submenus. Our menubar will contain
<?xml version="1.0" encoding="UTF-8"?>
<interface>
<menu id="menubar">
<submenu>
<attribute name="label">File</attribute>
</submenu>
<submenu>
<attribute name="label">Edit</attribute>
</submenu>
<submenu>
<attribute name="label">Choices</attribute>
</submenu>
<submenu>
<attribute name="label">Help</attribute>
</submenu>
</menu>
</interface>
Maintenant, créons le fichier .py et utilisons GtkBuilder pour importer le fichier
from gi.repository import Gtk
import sys
class MyWindow(Gtk.ApplicationWindow):
def __init__(self, app):
Gtk.Window.__init__(self, title="MenuBar Example", application=app)
self.set_default_size(200, 200)
class MyApplication(Gtk.Application):
def __init__(self):
Gtk.Application.__init__(self)
def do_activate(self):
win = MyWindow(self)
win.show_all()
def do_startup(self):
Gtk.Application.do_startup(self)
# a builder to add the UI designed with Glade to the grid:
builder = Gtk.Builder()
# get the file (if it is there)
try:
builder.add_from_file("menubar_basis.ui")
except:
print("file not found")
sys.exit()
# we use the method Gtk.Application.set_menubar(menubar) to add the menubar
# to the application (Note: NOT the window!)
self.set_menubar(builder.get_object("menubar"))
app = MyApplication()
exit_status = app.run(sys.argv)
sys.exit(exit_status)
Démarrez maintenant l'application python. Vous devriez voir quelque chose qui ressemble à l'image en haut de cette page.
Commençons par ajouter 2 éléments au menu section
contenant ces éléments au SouMenu Fichier
. Le fichier
]]>
En suivant ce modèle, ajoutez maintenant les éléments Copier
et Coller
au SousMenu Édition
et un élément À propos
au SousMenu Aide
.
Dans le fichier Python, créons les actions « Nouveau » et « Quitter » et connectons-les à une fonction de rappel ; par exemple, créons « new » de cette façon :
new_action = Gio.SimpleAction.new("new", None)
new_action.connect("activate", self.new_callback)
et la fonction de rappel de « new » de cette façon :
def new_callback(self, action, parameter):
print "You clicked \"New\""
Now, in the XML file, we connect the menu items to the actions in the XML file by adding the "action" attribute:
New
app.new
]]>
Notez que pour une action relative à l'application, nous utilisons le préfixe app.
, et que pour une action relative à la fenêtre, nous utilisons le préfixe win.
.
Finalement, nous ajoutons l'action à l'application ou à la fenêtre dans le fichier python - ainsi, par exemple, app.new
est ajouté à l'application dans la méthode do_startup(self)
de cette façon :
self.add_action(new_action)
See for a more detailed explanation of signals and callbacks.
Ci-dessus, nous créons les actions « new » et « open » comme faisant partie de la classe MyApplication. Les actions qui gèrent l'application elle-même (comme « quit »), doivent être créées de la même façon.
Quelques actions, comme « copy » et « paste » gèrent la fenêtre, pas l'application. Les actions gérant la fenêtre doivent être créées dans la classe window.
The complete example files contain both application actions and window actions. The window actions are the ones usually included in the application menu also. It is not good practice to include window actions in the application menu. For demonstration purposes, the complete example files which follow include XML in the UI file which creates the application menu which includes a "New" and "Open" item, and these are hooked up to the same actions as the menubar items of the same name.
Les lignes 30 à 80 inclue de décrivent le code XML utilisé pour créer le menu
les actions créées jusqu'à présent sont sans état (stateless), c-à-d. qu'elles ne prennent pas ni ne dépendent pas d'un état définit par l'action elle-même. Par contre, les actions que nous avons besoin de créer pour le SousMenu Choix sont avec état (stateful). Voici un exemple de création d'une action stateful :
shape_action = Gio.SimpleAction.new_stateful("shape", GLib.VariantType.new('s'), GLib.Variant.new_string('line'))
où les variables de la méthode sont : le nom, le type de paramètre (dans ce cas, une chaîne - voyez ici pour une liste complète des significations des caractères), l'état initial (dans ce cas, « line » - dans le cas d'une valeur boléenne True
, il devrait être Glib.Variant.new_boolean(True)
et ainsi de suite. Voyez ici pour consulter une liste complète)
Après avoir créé l'ActionSimple stateful, nous la connectons à la fonction de rappel et nous l'ajoutons à la fenêtre (ou à l'application selon le cas) comme auparavant :
shape_action.connect("activate", self.shape_callback)
self.add_action(shape_action)
<?xml version="1.0" encoding="UTF-8"?>
<interface>
<menu id="menubar">
<submenu>
<attribute name="label">File</attribute>
<section>
<item>
<attribute name="label">New</attribute>
<attribute name="action">app.new</attribute>
</item>
<item>
<attribute name="label">Quit</attribute>
<attribute name="action">app.quit</attribute>
</item>
</section>
</submenu>
<submenu>
<attribute name="label">Edit</attribute>
<section>
<item>
<attribute name="label">Copy</attribute>
<attribute name="action">win.copy</attribute>
</item>
<item>
<attribute name="label">Paste</attribute>
<attribute name="action">win.paste</attribute>
</item>
</section>
</submenu>
<submenu>
<attribute name="label">Choices</attribute>
<submenu>
<attribute name="label">Shapes</attribute>
<section>
<item>
<attribute name="label">Line</attribute>
<attribute name="action">win.shape</attribute>
<attribute name="target">line</attribute>
</item>
<item>
<attribute name="label">Triangle</attribute>
<attribute name="action">win.shape</attribute>
<attribute name="target">triangle</attribute>
</item>
<item>
<attribute name="label">Square</attribute>
<attribute name="action">win.shape</attribute>
<attribute name="target">square</attribute>
</item>
<item>
<attribute name="label">Polygon</attribute>
<attribute name="action">win.shape</attribute>
<attribute name="target">polygon</attribute>
</item>
<item>
<attribute name="label">Circle</attribute>
<attribute name="action">win.shape</attribute>
<attribute name="target">circle</attribute>
</item>
</section>
</submenu>
<section>
<item>
<attribute name="label">On</attribute>
<attribute name="action">app.state</attribute>
<attribute name="target">on</attribute>
</item>
<item>
<attribute name="label">Off</attribute>
<attribute name="action">app.state</attribute>
<attribute name="target">off</attribute>
</item>
</section>
<section>
<item>
<attribute name="label">Awesome</attribute>
<attribute name="action">app.awesome</attribute>
</item>
</section>
</submenu>
<submenu>
<attribute name="label">Help</attribute>
<section>
<item>
<attribute name="label">About</attribute>
<attribute name="action">win.about</attribute>
</item>
</section>
</submenu>
</menu>
<menu id="appmenu">
<section>
<item>
<attribute name="label">New</attribute>
<attribute name="action">app.new</attribute>
</item>
<item>
<attribute name="label">Quit</attribute>
<attribute name="action">app.quit</attribute>
</item>
</section>
</menu>
</interface>
from gi.repository import Gtk
from gi.repository import GLib
from gi.repository import Gio
import sys
class MyWindow(Gtk.ApplicationWindow):
def __init__(self, app):
Gtk.Window.__init__(self, title="MenuBar Example", application=app)
self.set_default_size(200, 200)
# action without a state created (name, parameter type)
copy_action = Gio.SimpleAction.new("copy", None)
# connected with the callback function
copy_action.connect("activate", self.copy_callback)
# added to the window
self.add_action(copy_action)
# action without a state created (name, parameter type)
paste_action = Gio.SimpleAction.new("paste", None)
# connected with the callback function
paste_action.connect("activate", self.paste_callback)
# added to the window
self.add_action(paste_action)
# action with a state created (name, parameter type, initial state)
shape_action = Gio.SimpleAction.new_stateful(
"shape", GLib.VariantType.new('s'), GLib.Variant.new_string('line'))
# connected to the callback function
shape_action.connect("activate", self.shape_callback)
# added to the window
self.add_action(shape_action)
# action with a state created
about_action = Gio.SimpleAction.new("about", None)
# action connected to the callback function
about_action.connect("activate", self.about_callback)
# action added to the application
self.add_action(about_action)
# callback function for copy_action
def copy_callback(self, action, parameter):
print("\"Copy\" activated")
# callback function for paste_action
def paste_callback(self, action, parameter):
print("\"Paste\" activated")
# callback function for shape_action
def shape_callback(self, action, parameter):
print("Shape is set to", parameter.get_string())
# Note that we set the state of the action!
action.set_state(parameter)
# callback function for about (see the AboutDialog example)
def about_callback(self, action, parameter):
# a Gtk.AboutDialog
aboutdialog = Gtk.AboutDialog()
# lists of authors and documenters (will be used later)
authors = ["GNOME Documentation Team"]
documenters = ["GNOME Documentation Team"]
# we fill in the aboutdialog
aboutdialog.set_program_name("MenuBar Example")
aboutdialog.set_copyright(
"Copyright \xc2\xa9 2012 GNOME Documentation Team")
aboutdialog.set_authors(authors)
aboutdialog.set_documenters(documenters)
aboutdialog.set_website("http://developer.gnome.org")
aboutdialog.set_website_label("GNOME Developer Website")
# to close the aboutdialog when "close" is clicked we connect the
# "response" signal to on_close
aboutdialog.connect("response", self.on_close)
# show the aboutdialog
aboutdialog.show()
# a callback function to destroy the aboutdialog
def on_close(self, action, parameter):
action.destroy()
class MyApplication(Gtk.Application):
def __init__(self):
Gtk.Application.__init__(self)
def do_activate(self):
win = MyWindow(self)
win.show_all()
def do_startup(self):
# FIRST THING TO DO: do_startup()
Gtk.Application.do_startup(self)
# action without a state created
new_action = Gio.SimpleAction.new("new", None)
# action connected to the callback function
new_action.connect("activate", self.new_callback)
# action added to the application
self.add_action(new_action)
# action without a state created
quit_action = Gio.SimpleAction.new("quit", None)
# action connected to the callback function
quit_action.connect("activate", self.quit_callback)
# action added to the application
self.add_action(quit_action)
# action with a state created
state_action = Gio.SimpleAction.new_stateful(
"state", GLib.VariantType.new('s'), GLib.Variant.new_string('off'))
# action connected to the callback function
state_action.connect("activate", self.state_callback)
# action added to the application
self.add_action(state_action)
# action with a state created
awesome_action = Gio.SimpleAction.new_stateful(
"awesome", None, GLib.Variant.new_boolean(False))
# action connected to the callback function
awesome_action.connect("activate", self.awesome_callback)
# action added to the application
self.add_action(awesome_action)
# a builder to add the UI designed with Glade to the grid:
builder = Gtk.Builder()
# get the file (if it is there)
try:
builder.add_from_file("menubar.ui")
except:
print("file not found")
sys.exit()
# we use the method Gtk.Application.set_menubar(menubar) to add the menubar
# and the menu to the application (Note: NOT the window!)
self.set_menubar(builder.get_object("menubar"))
self.set_app_menu(builder.get_object("appmenu"))
# callback function for new
def new_callback(self, action, parameter):
print("You clicked \"New\"")
# callback function for quit
def quit_callback(self, action, parameter):
print("You clicked \"Quit\"")
sys.exit()
# callback function for state
def state_callback(self, action, parameter):
print("State is set to", parameter.get_string())
action.set_state(parameter)
# callback function for awesome
def awesome_callback(self, action, parameter):
action.set_state(GLib.Variant.new_boolean(not action.get_state()))
if action.get_state().get_boolean() is True:
print("You checked \"Awesome\"")
else:
print("You unchecked \"Awesome\"")
app = MyApplication()
exit_status = app.run(sys.argv)
sys.exit(exit_status)
Les étiquettes peuvent contenir des mnémoniques. Les mnémoniques sont les caractères soulignés dans l'étiquette et sont utilisés pour se déplacer à l'aide des touches du clavier. Par exemple, « _Fichier » au lieu de seulement « Fichier » dans l'attribut barredemenu.ui de l'étiquette.
Vous pouvez voir les mnémoniques en appuyant sur la touche
Des raccourcis clavier peuvent être explicitement ajoutés aux définitions de l'interface utilisateur. Il est par exemple usuel de pouvoir quitter une application en appuyant sur la combinaison
<Primary>q]]>
will create the Quit
label item. Here, "Primary" refers to the
_Quit
app.quit
<Primary>q
]]>
Since GNOME applications are being translated into many languages, it is important that the strings in your application are translatable. To make a label translatable, simple set translatable="yes"
:
Quit]]>
Dans cet exemple, les éléments suivants sont utilisés :
GSimpleAction
GtkBuilder