使用字典的Python控制台菜单

1 投票
1 回答
4943 浏览
提问于 2025-04-18 12:35

我正在用Python 2.7开发一个Windows应用程序,需要一个简单的控制台菜单,比如:

  1. 做一些事情
  2. 做其他事情
  3. 退出

会有几个菜单,主菜单会链接到其他菜单。所以我想避免写一堆类似if input == "1"的代码。就像这个StackOverflow链接里提到的那样。我的代码现在跳过了主菜单,直接执行了第二个菜单里的每个选项。我看了很多遍,但还是搞不清楚为什么会这样。

computer = ""

# need a class for each of the options in power_menu
class power:
    def logoff(self, computer):
        print "logging off " + computer

    def restart(self, computer):
        print "restarting " + computer

    def shutdown(self, computer):
        print "shutting down " + computer

def set_computer():
    global computer
    #os.system("cls")
    # optionally print the banner
    computer = raw_input("Computer: ")
    # check the computer is online

    # move to the main menu with the computer parameter
    menu().menu_main(computer)

def func_quit():
    sys.exit()

def invalid(computer):
    #os.system("cls")
    print "INVALID CHOICE!"
    menu().menu_main(computer)

class menu():
    def menu_main(self, computer):
        opts_main = {"1":("Power Options", self.menu_power(computer)),
            "2":("Service Options", self.menu_service(computer)),
            "3":("Service Tag & Warranty", self.menu_warranty(computer)),
            "4":("User Options", self.menu_user(computer)),
            "5":("Change Computer", set_computer),
            "6":("Quit hd-con", func_quit)
            }
        for key in sorted(opts_main.keys()):
            print "\t" + key + ":  " + opts_main[key][0]
        ans = raw_input("Selection: ")
        try:
            opts_main.get(ans, [None, invalid])[1]()
        except Exception, e:
            print e
        #men_sel()

    def menu_power(self, computer):
        opts_power = {"1":("Logoff", power().logoff(computer)),
            "2":("Restart", power().restart(computer)),
            "3":("Shutdown", power().shutdown(computer)),
            "4":("Main Menu", menu.menu_main),
            "5":("Quit hd-con", func_quit)
            }
        for key2 in sorted(opts_power.keys()):
            print "\t" + key2+":  " + opts_power[key2][0]
        ans2 = raw_input("Selection: ")
        try:
            opts_power.get(ans2)[1]()
            #pow_sel()
        except:
            raise

我上面的输出结果是这样的。

Computer: asdf
logging off asdf
restarting asdf
shutting down asdf
        1:  Logoff
        2:  Restart
        3:  Shutdown
        4:  Main Menu
        5:  Quit 
Selection:

我希望能得到一些关于如何在控制台菜单中使用字典的指导,或者对现有代码的修复建议,或者推荐一个更好的方向,而不是我现在看到的这些。

提前谢谢你们。

1 个回答

1

你把字典里的内容分配给了:

opts_main = {"1":("Power Options", self.menu_power(computer)), ...}

这实际上是在调用 menu_power,并把它返回的结果(None)存储在元组里。你可以使用比如说 functools.partial 这样的工具来避免这个问题:

from functools import partial 

opts_main = {"1":("Power Options", partial(self.menu_power, computer)), ...}

撰写回答