下面的代码有一个主菜单和一个子菜单。第一个菜单提示加载并选择一个选项将加载另一个"页面"有更多的选择。我无法弄清楚如何从这里到另一个子部分。例如,称为sub2。
让我们说当选择选项1时,它会提示你选择两个子选项option1_sub2_1和option1_sub2_2。
让我们说当你选择选项2时,它会提示选项2_sub2_1 option2_sub2_2
我有一组选项存储为: menu_actions = { ' main_menu':main_menu, ' 1':一, ' 2':两个, ' b':回来了, ' q':退出, }
可以像这样设置它: option1_sub2 = { ' 1':一, ' 2':两个, } 和 option2_sub2 = { ' 1':一, ' 2':两个, }
这样我可以为不同的sub2项重复使用相同的数字。这可能吗?
这是我的第一个代码项目,我无法通过这部分。任何帮助将不胜感激。
代码:
import sys, os
# Main definition - constants
menu_actions = {}
# =======================
# MENUS FUNCTIONS
# =======================
# Main menu (display list on screen)
def main_menu():
os.system('clear')
print "1. Option"
print "2. Option"
choice = raw_input(" >> ")
exec_menu(choice)
return
# Choose a menu
def exec_menu(choice):
os.system('clear')
ch = choice.lower()
if ch == '':
menu_actions['main_menu']()
else:
try:
menu_actions[ch]()
except KeyError:
print "Invalid selection, please try again.\n"
menu_actions['main_menu']()
return
# =======================
# SUB MENUS
# =======================
# Back to main menu
def back():
menu_actions['main_menu']()
# Exit program
def exit():
sys.exit()
# Option1
def one():
print "Option 1"
print (30 * '-')
print "Sub Option 1"
print "Sub Option 2"
print "[B]ack"
print "[Q]uit"
choice = raw_input(" >> ")
exec_menu(choice)
return
# FTP
def two():
print (30 * '-')
print "Sub Option 1"
print "Sub Option 2"
print "[B]ack"
print "[Q]uit"
choice = raw_input(" >> ")
exec_menu(choice)
return
# =======================
# MENUS DEFINITIONS
# =======================
# Menu definition
menu_actions = {
'main_menu': main_menu,
'1': one,
'2': two,
'b': back,
'q': exit,
}
# =======================
# MAIN PROGRAM
# =======================
# Main Program
if __name__ == "__main__":
# Launch main menu
main_menu()
答案 0 :(得分:0)
首先将其抽象出来
首先创建一个方法,该方法将持续提示输入,直到达到给定的输入结果
def input_option(prompt,options):
while True:
result = raw_input(prompt)
if result in option: return result
print "Invalid Option Selected %r"%result
使用print input_option("Enter 1 or 2 or Three",["1","2","Three"])
现在抽象出一个显示菜单并从菜单中获取输入的功能
def select_menu(options):
print "Select From the choices Below:"
options = []
for option_text,input_value in options:
print option_text
options.append(input_value)
return input_option(">>>",options)
您可以像
一样进行测试options = [("1> option 1","1"),("2> option 2","2")]
print select_menu(options)
options2 = [("[B]ack","B"),("[Q]uit","Q")]
print select_menu(options2)
然后你要做的就是将行动映射到输入
menu_otions = [("Show Menu [1]","1"),("Show Menu [2]","2"),("[Q]uit","Q")]
menu_actions = {"1":show_menu1,"2":show_menu2,"Q":sys.exit