Search code examples
pythongetch

Trouble in detecting key presses in python using getch


I'm new to python and I'm trying to make a console game. To detect key presses i'm using getch ( https://github.com/joeyespo/py-getch ). But when I press a the code starts repeating.

key = getch()
while (True):
    if (key == 'a'):
        principal.adicionaragua()
        principal.gastaragua()
        principal.aumentardias()
        principal.estado()
        time.sleep(2)
        clear()

Edit: I'm using windows and python 2.7


Solution

  • You need to get key inside your loop. Otherwise, it will always be 'a' since you do not check inside your loop.

    while (True):
        key = getch()
        if (key == 'a'):
            principal.adicionaragua()
            principal.gastaragua()
            principal.aumentardias()
            principal.estado()
            time.sleep(2)
            clear()