0

The program I wrote is meant to be a menu navigable through live keyboard inputs with the keyboard module; unlike standard menus created in python which are navigated through set user inputs (input()) this menu should have a scroll like affect when using it. Code:

def MenuInterface():
    import keyboard
    MenuList = ["""Welcome to Empires Shell
    > [PLAY]
    [HELP]
    [CREDITS]
    [EXIT]
    """, """Welcome to Empires Shell
    [PLAY]
    > [HELP]
    [CREDITS]
    [EXIT]""", """Welcome to Empires Shell
    [PLAY]
    [HELP]
    > [CREDITS]
    [EXIT]
    """, """Welcome to Empires Shell
    [PLAY]
    [HELP]
    [CREDITS]
    > [EXIT]
    """]
    print (MenuList[0])
    x = 0
    while True: #This is the actual loop where I'm encountering my error
        if keyboard.read_key() == "s":
            x = x + 1
            if x == -1:
                x = 3
                print (MenuList[x])
            elif x == 4:
                x = 0
                print (MenuList[x])
            else:
                print (MenuList[x])
       


MenuInterface()

Running Returns:

Welcome to Empires Shell
    > [PLAY]
    [HELP]
    [CREDITS]
    [EXIT]

After typing "s" into the shell, returns:

Welcome to Empires Shell
    [PLAY]
    > [HELP]
    [CREDITS]
    [EXIT]
Welcome to Empires Shell
    [PLAY]
    [HELP]
    > [CREDITS]
    [EXIT]

As you can see the function, keyboard.read ran twice for a single input. Do you know why? And if so how can I fix this? Thanks!

CK Pixel
  • 7
  • 2

1 Answers1

0

The description for keyboard.read_key() is:

Blocks until a keyboard event happens, then returns that event's name or, if missing, its scan code.

This function returns raw keyboard scancodes, which means it will return individual key presses and releases (including modifier keys like Shift and Control). This type of detail is normally handled at OS level and application receive the actual character or control codes from it.

What you probably want is to use the builtin input() function, or if you want something higher level there are tools from external libraries like click.prompt().

Both these functions will require a carriage return and accept more than one character. If you want to act right away on every single character typed, see this question.

Thomas Guyot-Sionnest
  • 2,251
  • 22
  • 17