Search code examples
pythonalgorithm

Console select menu in python


I have a idea to create a console select menu in python like this:

Choose an option:
> 1. Do something 1 <
  2. Do something 2
  3. Do something 3
  4. Do something 4

If I press up arrow key, nothing happens. If I press the down one, the less than and greater than symbol would move up and down like this:

Choose an option:
  1. Do something 1 
> 2. Do something 2 <
  3. Do something 3
  4. Do something 4

But I dont know which Python 3 module would help me catch the key press instead of input(), and idk how I can align it correctly.

My solution for alignment is to print spaces (maybe?) and when the key press event is catches, the console will be cleared and it prints the select menu again instead of changing/modifying the strings.

Also, the options would be get from a list, which means this menu is expandable


Solution

  • You have to detect the keyboard key. As this detect key press in python? answer mentioned, Python has a keyboard module for it.

    You can install it with these command

    pip install keyboard
    

    Here's how it works

    • Define a menu number range, in this case is 1 until 4
    • Set a default selected menu and represent it with a number that we have defined, so it will appear when the user open the menu, in this case is 1
    • If a user press Up key, you have decrement the selected menu number, except if it has been on the first element of the range. And vice versa for the Down key, you have increment the selected menu number, except if it has been on the last element of the range.
    import keyboard
    
    selected = 1
    
    def show_menu():
        global selected
        print("\n" * 30)
        print("Choose an option:")
        for i in range(1, 5):
            print("{1} {0}. Do something {0} {2}".format(i, ">" if selected == i else " ", "<" if selected == i else " "))
    
    def up():
        global selected
        if selected == 1:
            return
        selected -= 1
        show_menu()
    
    def down():
        global selected
        if selected == 4:
            return
        selected += 1
        show_menu()
    
    show_menu()
    keyboard.add_hotkey('up', up)
    keyboard.add_hotkey('down', down)
    keyboard.wait()
    

    Sample