Blob Blame History Raw
<?xml version="1.0" encoding="utf-8"?>
<page xmlns="http://projectmallard.org/1.0/" xmlns:its="http://www.w3.org/2005/11/its" xmlns:xi="http://www.w3.org/2001/XInclude" type="guide" style="task" id="menubar.py" xml:lang="fr">
  <info>
  <title type="text">MenuBar (Python)</title>
  <link type="guide" xref="beginner.py#menu-combo-toolbar"/>
  <link type="seealso" xref="gmenu.py"/>
    <link type="next" xref="colorbutton.py"/>
    <revision version="0.1" date="2012-08-01" status="stub"/>

    <credit type="author copyright">
      <name>Tiffany Antopolski</name>
      <email its:translate="no">tiffany.antopolski@gmail.com</email>
      <years>2012</years>
    </credit>
    <credit type="author copyright">
      <name>Marta Maria Casetti</name>
      <email its:translate="no">mmcasetti@gmail.com</email>
      <years>2012</years>
    </credit>

    <desc>Un composant graphique qui contient des éléments graphiques GtkMenuItem</desc>
  
    <mal:credit xmlns:mal="http://projectmallard.org/1.0/" type="translator copyright">
      <mal:name>Luc Rebert,</mal:name>
      <mal:email>traduc@rebert.name</mal:email>
      <mal:years>2011</mal:years>
    </mal:credit>
  
    <mal:credit xmlns:mal="http://projectmallard.org/1.0/" type="translator copyright">
      <mal:name>Alain Lojewski,</mal:name>
      <mal:email>allomervan@gmail.com</mal:email>
      <mal:years>2011-2012</mal:years>
    </mal:credit>
  
    <mal:credit xmlns:mal="http://projectmallard.org/1.0/" type="translator copyright">
      <mal:name>Luc Pionchon</mal:name>
      <mal:email>pionchon.luc@gmail.com</mal:email>
      <mal:years>2011</mal:years>
    </mal:credit>
  
    <mal:credit xmlns:mal="http://projectmallard.org/1.0/" type="translator copyright">
      <mal:name>Bruno Brouard</mal:name>
      <mal:email>annoa.b@gmail.com</mal:email>
      <mal:years>2011-12</mal:years>
    </mal:credit>
  
    <mal:credit xmlns:mal="http://projectmallard.org/1.0/" type="translator copyright">
      <mal:name>Luis Menina</mal:name>
      <mal:email>liberforce@freeside.fr</mal:email>
      <mal:years>2014</mal:years>
    </mal:credit>
  </info>

  <title>MenuBar created using XML and GtkBuilder</title>
  <media type="image" mime="image/png" src="media/menubar.png"/>
  <p>Une BarreDeMenu créée avec XML et GtkBuilder.</p>

  <links type="section"/>

  <section id="xml"> <title>Création d'une BarreDeMenu avec XML</title>
   <p>Pour créer une BarreDeMenu avec XML :</p>
   <steps>
     <item><p>créez le fichier <file>barredemenu.ui</file> avec votre éditeur de texte favorit.</p></item>
     <item><p>Saisissez la ligne suivante en haut du fichier :</p>
           <code mime="application/xml"><![CDATA[
<?xml version="1.0"? encoding="UTF-8"?>]]></code>
     </item>
    <item><p>We want to create the interface which will contain our menubar and its submenus.  Our menubar will contain <gui>File</gui>, <gui>Edit</gui>, <gui>Choices</gui> and <gui>Help</gui> submenus. We add the following XML code to the file:</p>
    <code mime="application/xml">&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;interface&gt;
  &lt;menu id="menubar"&gt;
    &lt;submenu&gt;
      &lt;attribute name="label"&gt;File&lt;/attribute&gt;
    &lt;/submenu&gt;
    &lt;submenu&gt;
      &lt;attribute name="label"&gt;Edit&lt;/attribute&gt;
    &lt;/submenu&gt;
    &lt;submenu&gt;
      &lt;attribute name="label"&gt;Choices&lt;/attribute&gt;
    &lt;/submenu&gt;
    &lt;submenu&gt;
      &lt;attribute name="label"&gt;Help&lt;/attribute&gt;
    &lt;/submenu&gt;
  &lt;/menu&gt;
&lt;/interface&gt;
</code>
     </item>
     <item><p>Maintenant, créons le fichier .py et utilisons GtkBuilder pour importer le fichier <file>barredemenu.ui</file> que nous venons de faire.</p></item>
   </steps>
   </section>

   <section id="basis"> <title>Ajout de la BarreDeMenu à la fenêtre avec GtkBuilder</title>
<code mime="text/x-python">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)
</code>
<p>Démarrez maintenant l'application python. Vous devriez voir quelque chose qui ressemble à l'image en haut de cette page.</p>
</section>

<section id="xml2"> <title>Ajout d'éléments aux menus</title>
<p>Commençons par ajouter 2 éléments au menu <gui>Fichier</gui> : <gui>Nouveau</gui> et <gui>Quitter</gui>. Pour ce faire, ajoutons une <code>section</code> contenant ces éléments au SouMenu <code>Fichier</code>. Le fichier <file>barredemenu.ui</file> devrait ressembler à ceci (les lignes 6 à 13 comportent la section nouvellement ajoutée) :</p>

   <listing>
      <title>menubar.ui</title>
      <code mime="application/xml" style="numbered"><![CDATA[
<?xml version="1.0" encoding="UTF-8"?>
<interface>
  <menu id="menubar">
    <submenu>
      <attribute name="label">File</attribute>
      <section>
        <item>
          <attribute name="label">New</attribute>
        </item>
        <item>
          <attribute name ="label">Quit</attribute>
        </item>
      </section>
    </submenu>
    <submenu>
      <attribute name="label">Edit</attribute>
    </submenu>
    <submenu>
      <attribute name="label">Choices</attribute>
    </submenu>
    <submenu>
      <attribute name="label">Help</attribute>
    </submenu>
  </menu>
</interface>]]></code>
</listing>

  <p>En suivant ce modèle, ajoutez maintenant les éléments <code>Copier</code> et <code>Coller</code> au SousMenu <code>Édition</code> et un élément <code>À propos</code> au SousMenu <code>Aide</code>.</p>

  </section>

  <section id="actions">
    <title>Définition des actions</title>

    <p>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 :</p>
    <code mime="text/x-python">
new_action = Gio.SimpleAction.new("new", None)
new_action.connect("activate", self.new_callback)</code>

    <p>et la fonction de rappel de « new » de cette façon :</p>
    <code mime="text/x-python">
def new_callback(self, action, parameter):
    print "You clicked \"New\""</code>

    <p>Now, in the XML file, we connect the menu items to the actions in the XML file by adding the "action" attribute:</p>
    <code mime="text/x-python"><![CDATA[
<item>
  <attribute name="label">New</attribute>
  <attribute name="action">app.new</attribute>
</item>]]></code>

    <p>Notez que pour une action relative à l'application, nous utilisons le préfixe <code>app.</code>, et que pour une action relative à la fenêtre, nous utilisons le préfixe <code>win.</code>.</p>

    <p>Finalement, nous ajoutons l'action à l'application ou à la fenêtre dans le fichier python - ainsi, par exemple, <code>app.new</code> est ajouté à l'application dans la méthode <code>do_startup(self)</code> de cette façon :</p>
    <code mime="text/x-python">
self.add_action(new_action)</code>

    <p>See <link xref="signals-callbacks.py"/> for a more detailed explanation of signals and callbacks.</p> 

  </section>

  <section id="win-app"><title>Actions : application ou fenêtre ?</title>
    <p>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.</p>

    <p>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.</p>

    <p>The complete example files contain both application actions and window actions.  The window actions are the ones usually included in the <link xref="gmenu.py">application menu</link> 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.</p>
  </section>

  <section id="choices">
    <title>Le SousMenu Choix et les éléments avec leur état</title>
    <media type="image" mime="image/png" src="media/menubar_choices.png"/>
    <p>Les lignes 30 à 80 inclue de <link xref="menubar.py#xml-code"/> décrivent le code XML utilisé pour créer le menu <gui>Choix</gui> de l'interface utilisateur.</p>

    <p>les actions créées jusqu'à présent sont <em>sans état (stateless)</em>, 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 <em>avec état (stateful)</em>. Voici un exemple de création d'une action stateful :</p>
    <code mime="text/x-python">
shape_action = Gio.SimpleAction.new_stateful("shape", GLib.VariantType.new('s'), GLib.Variant.new_string('line'))</code>

    <p>où les variables de la méthode sont : le nom, le type de paramètre (dans ce cas, une chaîne - voyez <link href="http://developer.gnome.org/glib/unstable/glib-GVariantType.html">ici</link> 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 <code>True</code>, il devrait être <code>Glib.Variant.new_boolean(True)</code> et ainsi de suite. Voyez <link href="http://developer.gnome.org/glib/unstable/glib-GVariant.html">ici</link> pour consulter une liste complète)</p>

    <p>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 :</p>

    <code mime="text/x-python">
shape_action.connect("activate", self.shape_callback)
self.add_action(shape_action)</code>

  </section>

  <section id="xml-code">
    <title>Fichier XML complet de l'interface utilisateur de cet exemple</title>
    <code mime="application/xml" style="numbered">&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;interface&gt;
  &lt;menu id="menubar"&gt;
    &lt;submenu&gt;
      &lt;attribute name="label"&gt;File&lt;/attribute&gt;
      &lt;section&gt;
        &lt;item&gt;
          &lt;attribute name="label"&gt;New&lt;/attribute&gt;
          &lt;attribute name="action"&gt;app.new&lt;/attribute&gt;
        &lt;/item&gt;
        &lt;item&gt;
          &lt;attribute name="label"&gt;Quit&lt;/attribute&gt;
          &lt;attribute name="action"&gt;app.quit&lt;/attribute&gt;
        &lt;/item&gt;
      &lt;/section&gt;
    &lt;/submenu&gt;
    &lt;submenu&gt;
      &lt;attribute name="label"&gt;Edit&lt;/attribute&gt;
      &lt;section&gt;
        &lt;item&gt;
          &lt;attribute name="label"&gt;Copy&lt;/attribute&gt;
          &lt;attribute name="action"&gt;win.copy&lt;/attribute&gt;
        &lt;/item&gt;
        &lt;item&gt;
          &lt;attribute name="label"&gt;Paste&lt;/attribute&gt;
          &lt;attribute name="action"&gt;win.paste&lt;/attribute&gt;
        &lt;/item&gt;
      &lt;/section&gt;
    &lt;/submenu&gt;
    &lt;submenu&gt;
      &lt;attribute name="label"&gt;Choices&lt;/attribute&gt;
      &lt;submenu&gt;
        &lt;attribute name="label"&gt;Shapes&lt;/attribute&gt;
          &lt;section&gt;
            &lt;item&gt;
              &lt;attribute name="label"&gt;Line&lt;/attribute&gt;
              &lt;attribute name="action"&gt;win.shape&lt;/attribute&gt;
              &lt;attribute name="target"&gt;line&lt;/attribute&gt;
            &lt;/item&gt;
            &lt;item&gt;
              &lt;attribute name="label"&gt;Triangle&lt;/attribute&gt;
              &lt;attribute name="action"&gt;win.shape&lt;/attribute&gt;
              &lt;attribute name="target"&gt;triangle&lt;/attribute&gt;
            &lt;/item&gt;
            &lt;item&gt;
              &lt;attribute name="label"&gt;Square&lt;/attribute&gt;
              &lt;attribute name="action"&gt;win.shape&lt;/attribute&gt;
              &lt;attribute name="target"&gt;square&lt;/attribute&gt;
            &lt;/item&gt;
            &lt;item&gt;
              &lt;attribute name="label"&gt;Polygon&lt;/attribute&gt;
              &lt;attribute name="action"&gt;win.shape&lt;/attribute&gt;
              &lt;attribute name="target"&gt;polygon&lt;/attribute&gt;
            &lt;/item&gt;
            &lt;item&gt;
              &lt;attribute name="label"&gt;Circle&lt;/attribute&gt;
              &lt;attribute name="action"&gt;win.shape&lt;/attribute&gt;
              &lt;attribute name="target"&gt;circle&lt;/attribute&gt;
            &lt;/item&gt;
          &lt;/section&gt;
      &lt;/submenu&gt;
      &lt;section&gt;
        &lt;item&gt;
          &lt;attribute name="label"&gt;On&lt;/attribute&gt;
          &lt;attribute name="action"&gt;app.state&lt;/attribute&gt;
          &lt;attribute name="target"&gt;on&lt;/attribute&gt;
        &lt;/item&gt;
        &lt;item&gt;
          &lt;attribute name="label"&gt;Off&lt;/attribute&gt;
          &lt;attribute name="action"&gt;app.state&lt;/attribute&gt;
          &lt;attribute name="target"&gt;off&lt;/attribute&gt;
        &lt;/item&gt;
      &lt;/section&gt;
      &lt;section&gt;
        &lt;item&gt;
          &lt;attribute name="label"&gt;Awesome&lt;/attribute&gt;
          &lt;attribute name="action"&gt;app.awesome&lt;/attribute&gt;
        &lt;/item&gt;
      &lt;/section&gt;
    &lt;/submenu&gt;
    &lt;submenu&gt;
      &lt;attribute name="label"&gt;Help&lt;/attribute&gt;
      &lt;section&gt;
        &lt;item&gt;
          &lt;attribute name="label"&gt;About&lt;/attribute&gt;
          &lt;attribute name="action"&gt;win.about&lt;/attribute&gt;
        &lt;/item&gt;
      &lt;/section&gt;
    &lt;/submenu&gt;
  &lt;/menu&gt;
  &lt;menu id="appmenu"&gt;
    &lt;section&gt;
      &lt;item&gt;
        &lt;attribute name="label"&gt;New&lt;/attribute&gt;
        &lt;attribute name="action"&gt;app.new&lt;/attribute&gt;
      &lt;/item&gt;
      &lt;item&gt;
        &lt;attribute name="label"&gt;Quit&lt;/attribute&gt;
        &lt;attribute name="action"&gt;app.quit&lt;/attribute&gt;
      &lt;/item&gt;
    &lt;/section&gt;
  &lt;/menu&gt;
&lt;/interface&gt;
</code>
  </section>

  <section id="python-code">
    <title>Fichier Python complet de cet exemple</title>
    <code mime="text/x-python" style="numbered">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)
</code>
  </section>

  <section id="mnemonics-and-accelerators"><title>Mnémoniques et raccourcis clavier</title>
    <p>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.</p>
   <p>Vous pouvez voir les mnémoniques en appuyant sur la touche <key>Alt</key>. Pour ouvrir le menu <gui>Fichier</gui>, appuyez sur la combinaison de touches <keyseq><key>Alt</key><key>F</key></keyseq>.</p>

    <p>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 <keyseq><key>Ctrl</key><key>Q</key></keyseq> ou enregistrer un fichier avec <keyseq><key>Ctrl</key><key>S</key></keyseq>. Pour ajouter un raccourci clavier à la définition de l'interface, ajoutez simplement un attribut « accel » à l'élément.</p>
<p><code mime="application/xml"><![CDATA[<attribute name="accel">&lt;Primary&gt;q</attribute>]]></code> will create the <keyseq><key>Ctrl</key><key>Q</key></keyseq> sequence when added to the <code>Quit</code> label item.  Here, "Primary" refers to the <key>Ctrl</key> key on a PC or the <key>⌘</key> key on a Mac.</p>

  <code mime="application/xml"><![CDATA[
<item>
  <attribute name="label">_Quit</attribute>
  <attribute name="action">app.quit</attribute>
  <attribute name="accel">&lt;Primary&gt;q</attribute>
</item>]]></code>
  </section>

  <section id="translatable"><title>Chaînes de caractères traduisibles</title>
   <p>
   Since GNOME applications are being translated into <link href="http://l10n.gnome.org/languages/">many languages</link>, it is important that the strings in your application are translatable.  To make a label translatable, simple set <code>translatable="yes"</code>:
   </p>

     <code mime="application/xml"><![CDATA[<attribute name="label" translatable="yes">Quit</attribute>]]></code>

  </section>
  <section id="references">
    <title>Références API</title>
    <p>Dans cet exemple, les éléments suivants sont utilisés :</p>
    <list>
      <item><p><link href="http://developer.gnome.org/gio/unstable/GSimpleAction.html">GSimpleAction</link></p></item>
      <item><p><link href="http://developer.gnome.org/gtk3/unstable/GtkBuilder.html">GtkBuilder</link></p></item>
    </list>
  </section>
</page>