[Tutor] Creating sub-menus?

Kent Johnson kent37 at tds.net
Wed Dec 31 14:05:39 CET 2008


On Wed, Dec 31, 2008 at 2:22 AM, nathan virgil <sdragon1984 at gmail.com> wrote:
> I was reading the Non-Programmer's Tutorial for Python, and became really
> proud of myself when I realized I could create a menu for functions. I
> decided to try to take this one step further and see if I could create not
> just a menu, but a menu with <i>sub</i>-menus, too! Ultimately, the idea I
> came up with is this:
>
> Each menu is a function that prints out options, saves a raw_input as the
> variable choice, and returns choice. In the main menu, each option leads to
> a sub-menu. After choice is defined, however, the sub-menu "tags" the value
> of choice. Each sub-menu has it's own "tag", so that the program can tell
> the first choice of sub-menu A from the first choice of sub-menu B. A
> sub-menu function would end with code similar to:
>
> choice = raw_input("What's your choice?")
> choice = "a" + choice
> return choice
>
> Once I get all the menus and other functions out of the way, I get to the
> part of the code that actually chooses which function to run. Here, I start
> out with:
>
> choice = "start"
> current_menu = main_menu()
>
> Then create a loop of while choice !=q, run current_menu, and include a
> bunch of statements along the lines of:
>
> if choice == <value that leads to first sub-menu>:
>         current_menu = <function name for first sub-menu>
> elif choice == <value that leads to first non-menu function>
>         <first non-menu function>

You might want to look at the cmd module in the std lib, either as
something to build on or an example of dispatching commands:
http://docs.python.org/library/cmd.html

cmd uses introspection to dispatch to commands, rather than if/elif or
a hand-build dispatch dict.

There are a couple of enhancements to cmd, also:
http://catherine.devlin.googlepages.com/cmd2.html
http://code.google.com/p/cmdln/

HTH,
Kent


More information about the Tutor mailing list