代码之家  ›  专栏  ›  技术社区  ›  Jon_Computer

将模块启动到python菜单中

  •  1
  • Jon_Computer  · 技术社区  · 12 年前

    这可能是一个非常基本的愚蠢问题,但我无法做到这一点;我有一个这样的菜单(在Python 3中):

    boucle = True
    while boucle:
        print('''
            1−Gestion de listes
            2−Gestion de matrices
            0-Quitter
        ''')
    
        choix = input('Choissisez une commande:')
        if choix == '1':
            gestionliste() 
        elif choix == '2':
            print('Gestions de matrices')
        elif choix == '0':
            boucle = False
        else:
            print('Entrée erronée:Veuillez entrez loption 1,2 ou 0')
    

    (是的,顺便说一下,它是用法语写的),我希望当用户输入“1”作为选择时,我希望它启动我在同一.py文件中创建的函数 def thefunction():

    我想启动菜单 thefunction() 当用户输入“1”时。我尝试了很多事情,比如 if choix=='1' )function()、import function(),来自file.py import()。。。什么都不起作用。我想我还没有找到正确的方法?

    2 回复  |  直到 12 年前
        1
  •  1
  •   KodInc    12 年前

    您收到了什么错误?代码正在自行运行。

    whatever = True
    
    def thefunc():
        print("Works!")
    
    while whatever == True:
    
        print("""
            1-Whatever
            2-Whatever
            3-Whatever
        """)
    
        choice = input("Choice: ")
    
        if choice == "1":
            thefunc()
    
        elif choice == "2":
            print("...")
    
        elif choice == "0":
             whatever = False
    
        else:
            print("... again")
    

    只要在调用函数之前的某个时刻声明了该函数,代码就应该正常工作。代码中没有任何错误,但请确保正确声明了函数。

    干杯

        2
  •  0
  •   Hugh Bothwell    12 年前

    我对代码进行了一些包装,使其更易于使用(兼容Python2和3)。

    这是使其工作的机器,您可以剪切并粘贴它:

    from collections import namedtuple
    
    # version compatibility shim
    import sys
    if sys.hexversion < 0x3000000:
        # Python 2.x
        inp = raw_input
    else:
        # Python 3.x
        inp = input
    
    def get_int(prompt, lo=None, hi=None):
        """
        Prompt for integer input
        """
        while True:
            try:
                value = int(inp(prompt))
                if (lo is None or lo <= value) and (hi is None or value <= hi):
                    return value
            except ValueError:
                pass
    
    # a menu option
    Option = namedtuple("Option", ["name", "function"])
    
    def do_menu(options, prompt="? ", fmt="{:>2}: {}"):
        while True:
            # show menu options
            for i,option in enumerate(options, 1):
                print(fmt.format(i, option.name))
    
            # get user choice
            which = get_int(prompt, lo=1, hi=len(options))
    
            # run the chosen item
            fn = options[which - 1].function
            if fn is None:
                break
            else:
                fn()
    

    然后你可以这样使用它:

    def my_func_1():
        print("\nCalled my_func_1\n")
    
    def my_func_2():
        print("\nCalled my_func_2\n")
    
    def main():
        do_menu(
            [
                Option("Gestion de listes",   my_func_1),
                Option("Gestion de matrices", my_func_2),
                Option("Quitter",             None)
            ],
            "Choissisez une commande: "
        )
    
    if __name__=="__main__":
        main()