Question

I would like to dynamically print text in the terminal using curses but the following code doesn't display the key up/down text when this kind of key is pressed, whereas the loop text is updated. What have I done wrong ? I'm on a Mac OS Maverick.

import curses
import time

screen = curses.initscr()

curses.noecho()
curses.curs_set(0)
screen.keypad(1)
screen.nodelay(1)
i = 0

while True:
    i += 1

    event = screen.getch()
    screen.clear()

    if event == ord("q"):
        break

    elif event == curses.KEY_UP:
        screen.addstr("The User Pressed UP", curses.A_REVERSE)
        time.sleep(3)

    elif event == curses.KEY_DOWN:
        screen.addstr("The User Pressed DOWN", curses.A_BLINK)
        time.sleep(3)

    else:
        screen.addstr("Loop {0}".format(i))

curses.endwin()

I have tested the second code above and it works well. Very strange for me...

import curses

screen = curses.initscr()

curses.noecho()
curses.curs_set(0)
screen.keypad(1)
screen.nodelay(1)
i = 0

while True:
    i += 1

    event = screen.getch()

    if event == ord("q"):
        break

    elif event == curses.KEY_UP:
        screen.clear()
        screen.addstr(
            "The User Pressed UP in the loop {0}".format(i),
            curses.A_REVERSE
        )

    elif event == curses.KEY_DOWN:
        screen.clear()
        screen.addstr(
            "The User Pressed DOWN in the loop {0}".format(i),
            curses.A_BLINK
        )

curses.endwin()
Was it helpful?

Solution

The solution is to use screen.refresh().

import curses
import time

screen = curses.initscr()

curses.noecho()
curses.curs_set(0)
screen.keypad(1)
screen.nodelay(1)

i = 0

while True:
    i += 1

    event = screen.getch()
    screen.clear()

    if event == ord("q"):
        break

    elif event == curses.KEY_UP:
        screen.addstr("The User Pressed UP", curses.A_REVERSE)
        screen.refresh()
        time.sleep(2)

    elif event == curses.KEY_DOWN:
        screen.addstr("The User Pressed DOWN", curses.A_BLINK)
        screen.refresh()
        time.sleep(2)

    else:
        screen.addstr("Loop {0}".format(i))

curses.endwin()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top