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