2

I have to make a program with a text based menu system for a school project. It includes a main menu and multiple sub-menus. I have made my current version of the menu with LOTS of if-statements, prints and inputs. But it is neither a elegant nor easy solution. I was hoping there was a easier / better way to create a menu.

To be more precise, I need a method of calling the menu (to display it) after which I can choose an option, which then executes some code.

The structure looks as follows.

  • Input data Filters
  • Filters
    • Add filter
      • Type 1
      • Type 2
      • Type 3
    • Remove filter
    • Edit filter.
  • Do calculations
    • Mean
    • Standard variation
    • etc.
  • Create plot
  • Exit
Rewned
  • 61
  • 4

2 Answers2

1

The easiest way to handle this kind of problem is by recursion. Once you establish a useful data structure it can be handled recursively quite easily, since the job of creating a sub-menu is essentially the same as creating a menu.

In the solution below I define the menu as a tuple. The items in the menu are either the commands, represented as strings, or sub-menus, represented by nested tuples.

menu_data = (
    "Input data filters",
    ("Filters",
     ("Type 1",
      "Type 2",
      "Type 3"),
     "Remove Filter",
     "Edit Filter"),
    "Do Calculations",
    ("Mean",
     "Std Deviation",
     "etc"),
    "Create Plot",
    "Exit"
)

def make_menu(menu, indent=0):
    for item in menu:
        if type(item) == tuple:
            make_menu(item, indent+1)
        else:
            print(" "*indent+item)

make_menu(menu_data)

This should print the structure you require.

holdenweb
  • 33,305
  • 7
  • 57
  • 77
  • That istn't quite what I'm looking for. It is not the process of printer the menu, it is the process of interacting with it. Sidenote only the current layer of the menu should be visible. I have an idea that class's would be the way to go, but have absolutely no idea how it would / should be implemented. – Rewned Jan 07 '16 at 22:59
  • When you say "interacting with it" do you mean how to make sure that selection of a particular menu entry runs a specific piece of code or do you mean showing the top-level items, then the submenu associated with the menu item if it's a sub-menu? It might be a good idea to add more detail to the question or you will never the answer you need. – holdenweb Jan 08 '16 at 00:12
  • Added some detail, hope it's enough. – Rewned Jan 08 '16 at 00:23
0

Use the plot functions to plot menu's. You can import menus that are already made and then modify them so they suit what you want. Ploted windows's can interact with your mouse and and keyboard to move through the menu and select a locations in it. You can make it look like a text menu, with the only diference it is in a window instead of a shell. The library "pygame" has a lot of this.

I hope this helps.