[Tutor] Is this the preferred way to change terminal screen color using curses?
boB Stepp
robertvstepp at gmail.com
Sat Mar 2 16:16:15 EST 2019
I wanted to be able to change the background screen color of a
terminal window using curses. My weak Google-Foo did not turn up a
clear example of how to do this despite much searching. The two
_obvious_curses methods to attempt this seemed to be
window.bkgdset(ch, attr) to initially set a window's background
attributes and window.bkgd(ch, attr) to change them to new values.
The thing that has puzzled me is that "ch" is a mandatory parameter to
supply. So after a variety of experimental efforts I came up with the
following approach which seems to do what I want to do -- just change
the terminal's background color at will. But since I did *not* locate
any clear examples online on how to do this, I cannot help but wonder
if there is an easier approach to do what I want to do?
My code follows. As always I am open to any constructive criticism
even if it is off this email's topic, though this code is not meant to
be a polished product.
#!/usr/bin/env python3
import curses
def start_cli(stdscr):
max_height, max_width = stdscr.getmaxyx()
curses.init_pair(1, curses.COLOR_BLACK, curses.COLOR_CYAN)
PAIR_BLACK_ON_CYAN = curses.color_pair(1)
stdscr.clear()
stdscr.bkgdset(' ', PAIR_BLACK_ON_CYAN)
# Fill screen with spaces to color screen background:
for y in range(max_height):
try:
stdscr.addstr(y, 0, ' ' * max_width)
except curses.error as error:
if y == max_height - 1:
# Ignore error from writing to lower right-hand screen corner:
pass
else:
raise error
# Make cursor invisible to ensure *entire* screen is colored:
curses.curs_set(0)
stdscr.refresh()
# Pause program until user presses key:
stdscr.getkey()
# Change background screen color:
curses.init_pair(2, curses.COLOR_BLACK, curses.COLOR_RED)
PAIR_BLACK_ON_RED = curses.color_pair(2)
change_bkgd_color(stdscr, PAIR_BLACK_ON_RED)
stdscr.getkey()
def change_bkgd_color(window_obj, color_pair):
window_obj.bkgd(' ', color_pair)
if __name__ == '__main__':
input("Press ENTER to change screen to first color, then press"
" any key for next color change until the program exits.")
curses.wrapper(start_cli)
--
boB
More information about the Tutor
mailing list