近期遇到的一些场景,使用菜单式交互操作可以有效减少记忆负担,提升交互效率。从既有代码中剥离并完善形成了一个可以自定义菜单内容的 Python 脚本。
主函数及测试函数如下,使用方法可以参考测试用例子。
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 17 10:56:22 2022 at
Hami, Xinjiang Uygur Autonomous Regions, PRC.
@author: Farman
"""
import sys
#------------------------------------------------------------------------------
def pymenu(menu_items, lang="chs"):
"""
set lang to "chs" to show Simplified Chinese menus.
otherwise to show English menus.
"""
def GetInput(prompt="请输入"):
prompt += " : "
return input(prompt)
def show_invalid_input(index):
print()
print("%s :%s"%("输入无效" if lang=="chs" else "Invalid input", index))
print()
return
while True:
index = 1
print("")
print("操作选项" if lang=="chs" else "Menu Items")
print("--------------------------------------")
for title, func in menu_items:
print("%6s - %s"%(index, title)); index += 1
print()
print("%6s - %s"%(index, ("退出本级菜单" if lang=="chs" else "Exit this menu"))); index += 1
print("%6s - %s"%(index, ("退出程序" if lang=="chs" else "Exit program"))); index += 1
print("--------------------------------------")
index = GetInput("请输入操作序号" if lang=="chs" else "Input the index number")
if len(index):
try:
index = int(index)
if index < 1 or index > len(menu_items) + 2:
show_invalid_input(index)
continue
except:
show_invalid_input(index)
continue
# no exceptions and index is in [1, len(menu_items) + 2]
if index <= len(menu_items):
function = menu_items[index - 1][1]
function()
elif index == len(menu_items) + 1:
print("退出本级菜单。" if lang=="chs" else "Exit menu.")
break
elif index == len(menu_items) + 2:
print("退出程序。" if lang=="chs" else "Exit program.")
sys.exit(0)
print("now should exit.")
input("按回车键继续 ..." if lang=="chs" else 'Press "Enter" to continue ...')
return
#------------------------------------------------------------------------------------
def pymenu_test1():
def test1():
print("This is function test 1.")
return
def test2():
print("This is function test 2.")
return
menu_items = [
["Test-1", test1],
["Test-2", test2],
]
pymenu(menu_items, "eng")
return
def pymenu_test2(lang):
def sub_test1():
print("This is sub function test 1.")
return
def sub_test2():
print("This is sub function test 2.")
return
def test1():
menu_items = [
["Submenu-1", sub_test1],
["Submenu-2", sub_test2],
]
pymenu(menu_items, lang)
return
def test2():
print("This is function test 2.")
return
menu_items = [
["Test-1", test1],
["Test-2", test2],
]
pymenu(menu_items, lang)
return
#------------------------------------------------------------------------------
if __name__ == "__main__":
print("PyMenu Test")
print("Now test 1-level menus")
pymenu_test1()
print("Now test 2-level menus")
pymenu_test2('eng')
Enjoy.