0

I am trying to make a program where you can use the up and down arrow keys to increase a decrease a persons displayed heart rate.

import curses
running = True
heart_rate = 1
key = curses.KEY_RIGHT
print(heart_rate)
if key == curses.KEY_UP:
    heart_rate += 1
    print(heart_rate)
elif key == curses.KEY_DOWN:
    heart_rate -= 1
    print(heart_rate)
while heart_rate != 200:
    if heart_rate == 200 or heart_rate == 0:
        quit()

its just printing 1 and then not responding to the pressing of arrow keys.

Sayse
  • 42,633
  • 14
  • 77
  • 146
  • Most likely your code is stuck within the while loop, moving the `if/elif` inside the while loop might work but i'm not familiar with curses and how they handle key events – Sayse Aug 07 '19 at 15:46
  • What do you expect to change the value of `key`? – Fred Larson Aug 07 '19 at 15:49
  • It looks as though you are declaring `key` with the value `KEY_RIGHT` and nothing in the program is there to change it on a key press. – Josh Aug 07 '19 at 15:50
  • How about change the title for "How to use arrow keys with Python and curses?"? – Tim Nov 19 '19 at 15:44

1 Answers1

0

The variable key in your code is never set.

You should also consider reading the Python curses documentation to fully understand why you cannot use print() in a curses context.

Here is a functional revision of your algorithm:

import curses


def test(stdscr):
    heart_rate = 1

    while heart_rate != 200:
        stdscr.clear()
        stdscr.addstr(2, 2, str(heart_rate))
        stdscr.refresh()

        key = stdscr.getch()

        if key == curses.KEY_UP:
            heart_rate += 1
        elif key == curses.KEY_DOWN:
            heart_rate -= 1

        if not heart_rate:
            break

if __name__ == "__main__":
    curses.wrapper(test)

Tim
  • 2,052
  • 21
  • 30