Chi*_*nke 23 python curses colors
我无法让终端调色板与curses一起使用.
import curses
def main(stdscr):
curses.use_default_colors()
for i in range(0,7):
stdscr.addstr("Hello", curses.color_pair(i))
stdscr.getch()
curses.wrapper(main)
Run Code Online (Sandbox Code Playgroud)
这个python脚本产生以下屏幕:

但是,我的gnome-terminal调色板中有更多颜色.如何在curses中访问它们?
Chi*_*nke 40
以下我通过我自己的电脑(Ubuntu 14.04,python 3)进行了实验.
请考虑以下测试代码.将此添加到您的.bashrc:
# Set proper $TERM if we are running gnome-terminal
if [ "$COLORTERM" == "gnome-terminal" ]
then
TERM=xterm-256color
fi
Run Code Online (Sandbox Code Playgroud)
把它放在一个python文件中并运行它.
import curses
def main(stdscr):
curses.start_color()
curses.use_default_colors()
for i in range(0, curses.COLORS):
curses.init_pair(i + 1, i, -1)
try:
for i in range(0, 255):
stdscr.addstr(str(i), curses.color_pair(i))
except curses.ERR:
# End of screen reached
pass
stdscr.getch()
curses.wrapper(main)
Run Code Online (Sandbox Code Playgroud)
运行它将产生以下输出.

如您所见,颜色对1-16是前景色的终端调色板.
Mar*_*ers 13
终端'调色板'由终端应用程序本身设置,以将默认的curses颜色映射到特定于应用程序的"解释".如果您使用红色,终端可以选择将其显示为酒红色或樱桃红色,或者如果用户如此需要,则可以选择完全不同的东西.
换句话说,只需使用curses颜色(结合或不结合明亮或闪烁修饰符),就应该使用Just Work.
我认为这一curses.use_default_colors()呼吁只是提供透明度; 它是对use_default_colors()ncurses API函数的直接调用.ncurses颜色是基于调色板的; 你需要通过curses.init_pair()调用为每对编号设置自己的颜色属性,然后curses.color_pair()从调色板中选择一个颜色对,以显示具有该特定对的文本; 或直接为给定的addstr()调用构建文本属性.
我目前把这些行放在我的脚本前面.
curses.use_default_colors()
for i in range(0, curses.COLORS):
curses.init_pair(i, i, -1);
Run Code Online (Sandbox Code Playgroud)
我不知道它是否是最好的解决方案,但至少它会产生一些与终端调色板一致的颜色对.
我没有代表点将其作为对 Chiel 10 Brinke 出色答案的评论提交,因此我将在此处提供他的颜色脚本的更有用版本:
import curses
def main(stdscr):
curses.start_color()
curses.use_default_colors()
for i in range(0, curses.COLORS):
curses.init_pair(i + 1, i, -1)
stdscr.addstr(0, 0, '{0} colors available'.format(curses.COLORS))
maxy, maxx = stdscr.getmaxyx()
maxx = maxx - maxx % 5
x = 0
y = 1
try:
for i in range(0, curses.COLORS):
stdscr.addstr(y, x, '{0:5}'.format(i), curses.color_pair(i))
x = (x + 5) % maxx
if x == 0:
y += 1
except curses.ERR:
pass
stdscr.getch()
curses.wrapper(main)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
25753 次 |
| 最近记录: |