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="ko">
  <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>GtkMenuItem 위젯을 가진 위젯</desc>
  
    <mal:credit xmlns:mal="http://projectmallard.org/1.0/" type="translator copyright">
      <mal:name>조성호</mal:name>
      <mal:email>shcho@gnome.org</mal:email>
      <mal:years>2017</mal:years>
    </mal:credit>
  </info>

  <title>XML과 GtkBuilder로 만드는 MenuBar</title>
  <media type="image" mime="image/png" src="media/menubar.png"/>
  <p>XML과 GtkBuilder로 만든 MenuBar입니다.</p>

  <links type="section"/>

  <section id="xml"> <title>XML로 MenuBar 만들기</title>
   <p>XML로 메뉴 표시줄을 만들려면:</p>
   <steps>
     <item><p>원하는 텍스트 편집기로 <file>menubar.ui</file> 파일을 만드십시오.</p></item>
     <item><p>다음 줄을 파일 상단에 입력합니다:</p>
           <code mime="application/xml">
&lt;?xml version="1.0"? encoding="UTF-8"?&gt;</code>
     </item>
    <item><p>메뉴 표시줄과 하위 메뉴를 넣을 인터페이스를 만들겠습니다. 메뉴 표시줄에는 <gui>파일</gui>, <gui>편집</gui>, <gui>선택</gui> and <gui>도움말</gui> 하위 메뉴를 넣겠습니다. 다음 XML 코드를 파일에 넣겠습니다:</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>이제 .py 파일을 만들고 방금 만든 <file>menubar.ui</file>  파일을 가져올 때 GtkBuilder를 활용하겠습니다.</p></item>
   </steps>
   </section>

   <section id="basis"> <title>GtkBuilder로 창에 MenuBar 추가하기</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>이제 파이썬 프로그램을 실행하십시오 이 페이지의 상단의 그림과 비슷하게 나타납니다.</p>
</section>

<section id="xml2"> <title>항목을 메뉴에 추가하기</title>
<p><gui>파일</gui> 메뉴에 <gui>새로 만들기</gui>와 <gui>끝내기</gui> 메뉴 항목 2개 추가로 시작하겠습니다. <code>파일</code> 하위 메뉴에 이 항목과 <code>section</code>을 추가하면 됩니다. <file>menubar.ui</file> 파일은 다음과 같이 나타나야 합니다(6번째 줄부터 13번째 줄까지 새로 추가한 섹션 구성이 들어갑니다):</p>

   <listing>
      <title>menubar.ui</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;/item&gt;
        &lt;item&gt;
          &lt;attribute name ="label"&gt;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;/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>
</listing>

  <p>이런 방식으로 <code>편집</code> 하위 메뉴에 <code>복사</code> and a <code>붙여넣기</code>를 추가하고, <code>도움말</code> 하위 메뉴로 <code>정보</code> 항목을 추가할 수 있습니다.</p>

  </section>

  <section id="actions">
    <title>설정 동작</title>

    <p>파이썬 파일에서 콜백 함수로 연결한 "New"와 "Quit"에 대한 동작을 만들겠습니다. 예를 들어 "new"를 다음과 같이 만듭니다:</p>
    <code mime="text/x-python">
new_action = Gio.SimpleAction.new("new", None)
new_action.connect("activate", self.new_callback)</code>

    <p>그리고 "new"의 콜백 함수를 다음과 같이 만듭니다</p>
    <code mime="text/x-python">
def new_callback(self, action, parameter):
    print "You clicked \"New\""</code>

    <p>이제 XML 파일에서 "action" 속성을 추가하여 메뉴 항목을 XML 파일의 동작에 연결하겠습니다:</p>
    <code mime="text/x-python">
&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;</code>

    <p>참고로 프로그램과 관계있는 동작에는 <code>app</code> 접두부를 붙입니다. 창과 관계된 동작은 <code>win</code> 접두부를 붙입니다.</p>

    <p>마지막으로 파이썬 파일에서 프로그램 또는 창에 동작을 추가하겠습니다. 그래서 예를 들어 <code>app.new</code>는 다음과 같이 <code>do_startup(self)</code> 메서드에서 프로그램에 추가하겠습니다</p>
    <code mime="text/x-python">
self.add_action(new_action)</code>

    <p>시그널과 콜백 함수에 대한 자세한 내용은 <link xref="signals-callbacks.py"/>를 참고하십시오.</p> 

  </section>

  <section id="win-app"><title>동작: 프로그램 또는 창?</title>
    <p>위에서 MyApplication 클래스의 "new"와 "open" 동작을 만들었습니다. 프로그램 자체를 다루는 "quit" 같은 동작은 비슷하게 만듭니다.</p>

    <p>"copy"나 "paste" 같은 창을 다루는 일부 동작은, 프로그램에 넣지 않습니다. 창 동작은 창 클래스 부분에 만들어야합니다.</p>

    <p>완전한 예제 파일에는 프로그램 동작과 창 동작이 같이 들어있습니다. 창 동작은 보통  <link xref="gmenu.py">프로그램 메뉴</link> 에도 들어갑니다. 프로그램 메뉴에 창 동작이 들어가는건 좋은 실례가 아닙니다. 용도 증명 목적으로, 완전한 예제 파일에서는, "New"와 "Open" 항목이 들어간 프로그램 메뉴를 만드는 사용자 인터페이스 파일에 들어간 XML 내용을 따르며, 동일한 이름을 지닌 메뉴 표시줄 항목과 동일한 동작을 수행합니다.</p>
  </section>

  <section id="choices">
    <title>상태가 들어간 선택 하위 메뉴 및 항목</title>
    <media type="image" mime="image/png" src="media/menubar_choices.png"/>
    <p>30번째 줄 부터 80번째 줄 까지 <link xref="menubar.py#xml-code"/> 코드가 들어간 부분에서 <gui>선택</gui> 메뉴의 사용자 인터페이스를 만들 때 쓰는 XML 코드 예제를 시연합니다.</p>

    <p>여지껏 만든 동작은 <em>상태가 없는</em> 상황인데 동작 자체에 주어진 상태에 따르거나 상태 값을 유지하지 않습니다. 반면에 선택 하위 메뉴에 우리가 만들 동작은 <em>상태를 보유하고 있습니다</em>. 상태를 가진 동작을 만드는 예제는 다음과 같습니다:</p>
    <code mime="text/x-python">
shape_action = Gio.SimpleAction.new_stateful("shape", GLib.VariantType.new('s'), GLib.Variant.new_string('line'))</code>

    <p>메서드 변수 부분은 다음과 같습니다. 이름, 매개변수 형식(우리 같은 경우는 문자열입니다. 문자 의미에 대한 완전한 내용은 <link href="http://developer.gnome.org/glib/unstable/glib-GVariantType.html">여기</link> )에 있습니다), 초기 상태(이 경우 'line' 입니다. <code>True</code> 부울린 값의 경우는 <code>Glib.Variant.new_boolean(True)</code>여야 합니다. 완전한 내용은 <link href="http://developer.gnome.org/glib/unstable/glib-GVariant.html">이 부분</link> 참고)를 다룹니다.</p>

    <p>앞에서와 마찬가지로 상태가 들어간 SimpleAction을 만든 다음 콜백 함수로 연결하고 창(또는 지금 같은 경우는 프로그램)에 추가하겠습니다:</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>이 예제의 완전한 XML UI 파일</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>이 예제의 완전한 파이썬 파일</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>접근 키와 단축키</title>
    <p>레이블에는 접근 키가 들어갈 수 있습니다. 접근 키는 키보드로 탐색할 때 활용하는 레이블에 밑줄이 들어간 문자입니다. 접근 키는 접근키 문자 앞에 밑줄을 넣어 만듭니다. 예를 들어 menubar.ui 레이블 속성에서 "File" 대신 "_File"을 넣습니다.</p>
   <p>접근키는 <key>Alt</key> 키를 누르면 나타납니다. <keyseq><key>Alt</key><key>F</key></keyseq> 키를 누르면 <gui>파일</gui> 메뉴가 나타납니다.</p>

    <p>가속키는 UI 정의에 분명하게 추가할 수 있습니다. 예를 들어 일반적으로 프로그램을 끝내는 동작은 <keyseq><key>Ctrl</key><key>Q</key></keyseq> 키를 눌러 진행할 수 있고, 또는 파일을 저장하는 동작은 <keyseq><key>Ctrl</key><key>S</key></keyseq> 키를 눌러 진행할 수 있습니다. UI 정의에 가속키를 추가하려면 간단하게 항목의 "accel" 속성 값을 추가하면 됩니다.</p>
<p><code mime="application/xml">&lt;attribute name="accel"&gt;&amp;lt;Primary&amp;gt;q&lt;/attribute&gt;</code> 구문은 <code>Quit</code> 레이블 항목에 추가할 <keyseq><key>Ctrl</key><key>Q</key></keyseq> 키 조합 입력을 만듭니다. 여기서, "Primary"는 PC의 <key>Ctrl</key>키 또는 맥의 <key>⌘</key> 키를 따릅니다.</p>

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

  <section id="translatable"><title>번역할 문자열</title>
   <p>그놈 프로그램은 <link href="http://l10n.gnome.org/languages/">다양한 언어</link>로 번역하기에 프로그램 문자열을 번역할 수 있게 만들어 두는게 중요합니다. 레이블을 번역할 수 있게 하려면 간단히 <code>translatable="yes"</code>를 설정하십시오:</p>

     <code mime="application/xml">&lt;attribute name="label" translatable="yes"&gt;Quit&lt;/attribute&gt;</code>

  </section>
  <section id="references">
    <title>API 참고서</title>
    <p>이 예제는 다음 참고자료가 필요합니다:</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>