我正在开发 CLI 应用程序并使用 PyInquirer创建一个选择菜单。所以我创建的是一个选择菜单,它要求用户选择要做什么,选项是:
- view task,
- Add Task,
- Push up Task.
我创建了一个功能,当您选择查看任务时,它会提示另一组选择。然而,从这里我想返回主菜单。我似乎无法理解我需要这样做的逻辑。我知道我可以对所有可能的路径进行硬编码,但必须有更好的方法来做到这一点。我考虑过创建函数,但我能想到的唯一方法是互相调用,这是行不通的。
def main():
main_menu_selection = prompt(main_menu, style=custom_style_2)
# Part I reference below
if main_menu_selection['which_task']== 'View Tasks':
view_tasks_selection = prompt(view_tasks, style=custom_style_2)
if (view_tasks_selection['view_task']).lower() == 'daily':
print_tasks("daily")
# Function to return to menu
print("Press Enter to return to Main Menu")
user_input = input()
if user_input:
main_menu_selection = prompt(main_menu, style=custom_style_2)
# Here I would need it to go back to the if statement mentioned above
感谢您的指导或建议。
最佳答案
您可以将整个内容包装在 while True:
语句中,这样每当您完成任何路径时,您都会返回到主菜单选择。当你想退出时,只需使用break
退出循环即可。下面是一个简单的示例。
def main():
while True:
main_menu_selection = prompt(main_menu, style=custom_style_2)
# Part I reference below
if main_menu_selection['which_task']== 'View Tasks':
view_tasks_selection = prompt(view_tasks, style=custom_style_2)
if (view_tasks_selection['view_task']).lower() == 'daily':
print_tasks("daily")
else:
break
关于python - 如何在Python中返回到前一部分代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58913642/