Search code examples
pythonncursescurses

How can I add colour to a specific string using python curses?


For Example, I have string "Colour selected is red" How do I make only the word "red" red?

This is what I'm using to try and achieve this.

import curses

curses.start_color()
curses.init_pair(1, curses.COLOR_RED, curses.COLOR_BLACK)
win = curses.newwin(5 + window_height, window_width, 2, 4)

win.addstr(position + 2, 5, "Colour selected is " + "Red", curses.color_pair(1))

it's part of a bigger project so some info might be missing. But it does not work.


Solution

  • This works:

    import curses
    
    curses.initscr();
    
    window_height = curses.LINES - 2
    window_width = curses.COLS - 2
    position = 3
    
    curses.start_color()
    curses.init_pair(1, curses.COLOR_RED, curses.COLOR_BLACK)
    win = curses.newwin(5 + window_height, window_width, 2, 4)
    
    win.addstr(position + 2, 5, "Colour selected is " + "Red", curses.color_pair(1))
    
    win.getch()
    

    If you had reduced the problem to a simple, complete program, you would probably see the problem in your original program.

    Following up on comment: in curses, the addstr function applies the attribute (including color) to the whole string parameter. If you want to have different parts of the string with different attributes, you will have to make separate calls to addstr, one for each attribute as applied to parts of the original string. Something like this:

    win.addstr(position + 2, 5, "Colour selected is ")
    win.addstr("Red", curses.color_pair(1))