[Python] Console Menu Generator in Python

Discussão em 'Python' iniciado por Stack, Março 13, 2025.

  1. Stack

    Stack Membro Participativo

    As the title says, I'm writing a Console Menu Generator in Python. I have 2 classes, Menu and Item. But I get into troubles. Here is the code:

    class Menu:
    def AddItem(self,item):
    class Item:
    def __init__(self,text,ToDoNext):
    self.text=text
    ??????????????
    self.item.append(Item())
    def Show():
    for i in range(len(self.item)):
    print(str(i+1)+") "+str(self.item)+"\n")
    print("0) Back\n")
    option=int(input())
    self.item[option].????????????


    This code basically do the next:

    Main=Menu()
    Menu.AddItem("Open file",ToDo1)
    Menu.AddItem("Save file",ToDo2)
    Menu.Show()

    '''1) Open file
    2) Save file
    0) Back
    _
    '''


    If I write 1 and press enter should do the portion of code ToDo1, for example. The solution that I thought is the nextone:

    def ToDo1():
    print("Hello, world!")
    Menu.AddItem("Say Hello","ToDo1()")


    and use an eval() function inside the Show().

    But I'm not pretty sure this is not the correct way to do that.

    I would like you to show me a better way, and if you have ever do something like that (Console Menu Generator) to share the code and see another way of doing the same.

    Continue reading...

Compartilhe esta Página