aegirhall / console-menu

A simple Python menu system for building terminal user interfaces.
MIT License
366 stars 58 forks source link

How to get a return value when not using SelectionMenu #2

Closed txoof closed 5 years ago

txoof commented 6 years ago

When creating a menu as below, how does one get the index or value of the menu item that was chosen during the input? Is there a way to get the index or value from the SubmenuItem?

I've used SelectionMenu() successfully to do this, but can't see how to work with a mixture of items, functions and sub menus.

menu = ConsoleMenu('Select from the list')
menu_item_1 = MenuItem("Menu Item 1")
menu_item_2 = MenuItem("Menu Item 2")
menu_item_3 = MenuItem("Menu Item 3")
menu_item_4 = MenuItem("Menu Item 4")
submenu = SelectionMenu(["item1", "item2", "item3"], title="Selection Menu",
                            subtitle="These menu items return to the previous menu")

submenu_item = SubmenuItem("Submenu item", submenu=submenu)
submenu_item.set_menu(menu)

menu.append_item(menu_item_1)
menu.append_item(menu_item_2)
menu.append_item(menu_item_3)
menu.append_item(menu_item_4)
menu.append_item(submenu_item)
choice = menu.show()

menu.show() returns None

aegirhall commented 5 years ago

Hi @txoof Typically it isn't necessary to know the current menu option, as each individual menu item will have its own handler, which performs whatever actions are necessary for that menu item, then returns control back to the menu for the next selection.

However, if you really need to know what the currently-selected item is, you can do so with a separate thread, checking the menu's current_option property. A simple example:

def current_item_checker(menu):
    while True:
        print 'current menu option:', menu.current_option
        time.sleep(5)
.....
# then prior to calling menu.show()...
threading.Thread(target=current_item_checker, kwargs={'menu':menu}).start()