[Python] Dynamic submenu items with cursesmenu

Discussão em 'Python' iniciado por Stack, Julho 23, 2025.

  1. Stack

    Stack Membro Participativo

    I'm using Python's curses-menu package and understand how to make submenus in a menu when the menu is statically defined before .show() is called. I am trying to make a menu item which, when selected, will dynamically make the selected submenu's items. In other words, when I select an item, I want run code to, say, take some user input, and make something like a SelectMenu with each string as an item. Lastly, I then want to use the selected string as input to a function.

    Here's what I'm trying:

    # Import the necessary packages
    from cursesmenu import *
    from cursesmenu.items import *

    def work_with_selection(selection):
    print('You selected {}'.format(selection))

    def build_sub():
    items = []
    for i in range(3):
    item = input('Type an item: ')
    items.append(item)
    selection = SelectionMenu(items).get_selection(items)
    work_with_selection(selection)

    # Create the menu
    menu = CursesMenu("Title", "Subtitle")

    # Create some items

    # Dynamically build submenu
    build_item = FunctionItem("Build dynamic submenu", build_sub)

    menu.append_item(build_item)

    # Finally, we call show to show the menu and allow the user to interact
    menu.show()


    It appears to work except that once I chose Exit from the submenu, the parent menu redraws, and the cursor keys stop working. Instead of moving the selector, it give control-characters with letters as in the top left of this:

    ^[[B^[[A^[[B───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
    │ │
    │ Title │
    │ │
    │ Subtitle │
    │ 1 - Build dynamic submenu │
    │ 2 - Exit │
    └──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
    │ 4 - Exit │
    └──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘


    I'm using Python 3.

    Is using SelectionMenu the right way to go? If so, how do I fix the parent main menu once I return to it? If not, how should I make such a dynamic submenu creation?

    Continue reading...

Compartilhe esta Página