Search code examples
pythoncurses

How to colorize a word with curses while typing?


i'm new to curses library, and i am trying to colorize the stdin but haven't done yet. I wrote the following codes but they didn't work as i wish, can anyone help me to show how to colorize the stdin?

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import curses

stdscr = curses.initscr()
curses.start_color()
curses.init_pair(1, curses.COLOR_RED, curses.COLOR_BLACK)
stdscr.nodelay(1)

q = 1
x = set()

while q != ord("q"):
    if len(x) == 3:
        stdscr.addstr(0,0, "def", curses.color_pair(1))
    if q == ord("d"):
        x.add("d")
    elif q == ord("e"):
        x.add("e")
    elif q == ord("f"):
        x.add("f")
    q = stdscr.getch()

stdscr.getch()
curses.endwin()

Solution

  • Your problem appears to be the screen-updates. This version puts the updates after the x set is up-to-date:

    #!/usr/bin/env python3
    # -*- coding: utf-8 -*-
    
    import curses
    
    stdscr = curses.initscr()
    curses.start_color()
    curses.init_pair(1, curses.COLOR_RED, curses.COLOR_BLACK)
    curses.raw()
    curses.noecho()
    
    q = -1
    x = set()
    
    while q != ord("q"):
        if q >= 0:
            stdscr.addstr(chr(q))
        if q == ord("d"):
            x.add("d")
        elif q == ord("e"):
            x.add("e")
        elif q == ord("f"):
            x.add("f")
        else:
            x = set()
        if len(x) == 3:
            stdscr.addstr("\b\b\bdef", curses.color_pair(1))
            x = set()
        q = stdscr.getch()
    
    stdscr.getch()
    curses.endwin()