Search code examples
pythoncolorscurses

How do I set the window background color using curses and Python?


My goal: make a window background a particular color.

My current code:

import curses


def do_it(win):  # Shia LeBeouf!
    win.bkgd(' ', curses.COLOR_BLUE)
    win.addstr(1,1, "This is not blue")
    win.getch()

if __name__ == '__main__':
    curses.wrapper(do_it)

My expectation is that my window would be the color blue, with "This is not blue" appearing. Instead I get this window:

$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
$This$is$not$blue$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$

It's not even very blue.

I've also tried:

  • win.bkgd(curses.COLOR_BLUE) - appears to remove all spaces(?)
  • win.bkgdset(' ', curses.COLOR_BLUE) - seems to do the same thing

These, and more, to no avail.

The question then remains: how do I set the background color of a window in curses?


Solution

  • Apparently you have to specify your colors, using curses.init_pair before using them. Then you can use them with curses.color_pair:

    import curses
    
    
    def do_it(win):  # Shia LeBeouf!
        curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_BLUE)
        win.bkgd(' ', curses.color_pair(1) | curses.A_BOLD)
        win.addstr(1,1, "This is not blue")
        win.getch()
        win.bkgd(' ', curses.color_pair(1) | curses.A_BOLD | curses.A_REVERSE)
        win.addstr(1,1, "This is now blue")
        win.getch()
    
    if __name__ == '__main__':
        curses.wrapper(do_it)