Python — curses,设置边框颜色
2 个回答
0
William建议使用 attrset() 这个方法,确实不错。不过因为我刚开始接触Python的curses库,所以在能用上这个方法之前,我得先查点资料。
如果你也像我当时那样感到迷茫,这里有一个可以运行的程序示例,它可以显示一个蓝色边框:
#!/usr/bin/env python3
import curses
def main(stdscr):
curses.use_default_colors() # Make possible to use -1 in init_pair()
# To define colors, it's necessary to program a color pair. We are using
# the color pair 1. The -1 parameter below references the default color.
curses.init_pair(1, curses.COLOR_BLUE, -1)
stdscr.clear()
begin_x = 1
begin_y = 1
height = 3
width = 15
window = curses.newwin(height, width, begin_y, begin_x)
# Set the color and draw a box. Note that a refresh() is still necessary
window.attrset(curses.color_pair(1))
window.box()
# Reset the colors. The color pair 0 is always white on black
window.attrset(curses.color_pair(0))
window.addstr(1, 3, "Box Title")
window.refresh()
curses.curs_set(0) # Invisible cursor
window.getkey()
if __name__ == "__main__":
curses.wrapper(main) # Restore configuration after the program's end
我把这个代码保存为 colored_box.py
,然后用 python colored_box.py
来运行。这个代码是在Python 3.10.12版本上测试过的。
顺便说一下,我觉得 color_pair(0) 可能不是保持默认前景色和背景色的正确选项,但我现在没办法确认,因为我的终端是黑底白字。
1
好吧,这是一种给文字上色的方法,但通常来说,这不是最好的办法。我建议你使用attrset(),然后再添加字符串或边框。这样,边框和文字都会受到影响,而且这样做的开销更小。