Advertisement
gruntfutuk

menu dictionary based

Sep 1st, 2020
1,172
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.95 KB | None | 0 0
  1. """ Example dictionary based menu system"""
  2.  
  3. from collections import namedtuple  # to refer to dictionary values easily
  4.  
  5. def menu_option(menu):
  6.     header = "\nMenu\n"
  7.     __data__ = menu.get('__data__')
  8.     if __data__:
  9.         header = __data__.get('header', header)
  10.     print(header)
  11.     for option, details in menu.items():
  12.         if not option == "__data__":
  13.             print(f'{option}:  {details.desc}')
  14.     print('\n')
  15.     while True:
  16.         option = input('Option? ').strip().lower()
  17.         if option in menu and option != "__data__":
  18.             return menu[option]
  19.         print('Sorry, that option is not available')
  20.  
  21. # function for each menu option except quit/exit where None is assigned
  22. def option_1():
  23.     print('option_1')
  24.  
  25. def option_2():
  26.     print('option_2')
  27.  
  28. def option_3():
  29.     print('option_3')
  30.  
  31. def option_2_1():
  32.     print('option_2_1')
  33.  
  34. def option_2_2():
  35.     print('option_2_1')
  36.        
  37.        
  38. Menu = namedtuple('Menu', 'desc misc func')  # menu entries have three values, {<key>: (<desc>, <misc>, <func>)}
  39.                                              # can add whatever addition fields are required
  40.                                              # I used <func> to be the reference to the function to be called for
  41.                                              # the correspnding option
  42.  
  43. menu1 = {"1": Menu("option 1", "misc", option_1),
  44.          "2": Menu("option 2", "misc", option_2),
  45.          "3": Menu('option 3', "misc", option_3),
  46.          "q": Menu("quit", "", None),
  47.          "__data__": {"header": "\nExample top level menu\n"},
  48.            }
  49. menu2 = {"1": Menu("option 2.1", "misc", option_2_1),
  50.          "2": Menu("option 2.2", "misc", option_2_2),
  51.          "q": Menu("exit", "", None),
  52.          "__data__":  {"header": "\nExample second level menu\n"},
  53.         }
  54.  
  55. # example use
  56. while True:
  57.     menu1_choice = menu_option(menu1)
  58.     if not menu1_choice.func:
  59.         break
  60.     menu1_choice.func()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement