将模块加载到Python菜单中

1 投票
2 回答
667 浏览
提问于 2025-04-18 00:36

这可能是个非常基础的问题,但我就是搞不明白该怎么做;我有一个这样的菜单(用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():

我希望菜单在用户输入'1'时能调用thefunction()这个函数。我试过很多方法,比如在if choix=='1'之后写function()、import function()、from file.py import()……但是都不行。我想我还没找到正确的方法?

2 个回答

0

我把代码整理了一下,这样用起来更方便了(可以同时在Python 2和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()
1

你遇到了什么错误?这段代码本身是可以正常工作的。

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")

只要你在调用这个函数之前已经声明过它,你的代码就应该能正常运行。你的代码没有问题,但要确保你的函数声明是正确的。

祝好,

撰写回答