Python — curses,设置边框颜色

0 投票
2 回答
2406 浏览
提问于 2025-04-18 01:04

从Python的文档使用指南中,我们可以了解到如何给文本上色:首先要把字符串添加到一个窗口里,然后使用chgat()来给那个窗口里想要的字符指定颜色。

但我不太明白的是,如何改变用box()border()显示的框或边框的颜色。补充说明:在整个窗口上使用chgat()似乎并不会影响这个窗口的边框。

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(),然后再添加字符串或边框。这样,边框和文字都会受到影响,而且这样做的开销更小。

撰写回答