[Tutor] Menu data from file

Lie Ryan lie.1296 at gmail.com
Mon Apr 5 16:03:39 CEST 2010


On 04/05/10 17:39, Neven Goršić wrote:
> Thank you for mentioning the possible options.
> I already use option where I import .py module,
> but I run into troubles when making executable with py2exe.

Maybe you should elaborate what problems you're experiencing with
py2exe? Probably we can solve that instead of developing workarounds.

Many popular UI toolkit provides an XML-based menu file.
Here is one for PyGTK:
http://www.pygtk.org/pygtk2tutorial/sec-UIManager.html

You should better use your GUI toolkit's version instead of writing your
own.

> I suppose that XML approach is the most general method.
> Can you recommend a good introduction text (not for experts :-))
> and give more details about the tool ElementCTree.
> 
> Maybe it will be educational and interesting for other beginners too.

ElementTree is quite simple, though I don't think there are many good
tutorials about it (at least I can't find one). In the simplest use
case, you just use xml.etree.ElementTree.parse("menu.xml") and you can
iterate the tree like so:

import xml.etree.cElementTree as Et
menuxml = """
<menubar>
  <menu title="File">
    <menuitem title="Open File..." action="open_file"/>
    <menu title="Recent Files">
      <menuitem title="placeholder_1" action="recent_1"/>
      <menuitem title="placeholder_2" action="recent_2"/>
      <menuitem title="placeholder_3" action="recent_3"/>
    </menu>
    <menuitem title="Exit My Program" action="quit"/>
  </menu>
  <menu title="Edit">
    <menuitem title="Copy" action="copy_clipboard"/>
    <menuitem title="Paste" action="paste_clipboard"/>
  </menu>
</menubar>
"""
# root = Et.parse("menu.xml")
root = Et.fromstring(menuxml)

def parse(menutk, element):
    for menu in mbar:
        if menu.tag == 'menu':
            # have submenus, recurse
            submenutk = add_menu(menutk)
            parse(submenutk, menu)
        elif emnu.tag == 'menuitem':
            add_menuitem(menutk, menuitem)

or something like that.



More information about the Tutor mailing list