使用 python curses 更改输入文本的颜色

change color of input text using python curses

我正在使用 python 的 curses 包装器库开发文字游戏。 我希望用户输入的文本与游戏输出的文本颜色不同。我在为输出文本定义颜色对时没有遇到任何问题,但我无法弄清楚如何更改输入文本以在用户主动输入时显示不同的颜色。

目前,我使用 getstr() 方法获取所有输入。

python/curses 这可能吗?

谢谢, 伊恩

虽然您可以在 echo 开启的情况下初始化 Python curses 包装器,但如果您正在使用 curses wrapper,如果最初关闭 echo,例如,

    # Initialize curses 
    stdscr = curses.initscr()

    # Turn off echoing of keys, and enter cbreak mode, 
    # where no buffering is performed on keyboard input 
    curses.noecho()
    curses.cbreak()

如果 curses 没有回显,则您的程序必须进行一些回显。但是由于您使用的是 getstr,这意味着您已经打开了 echo,因为 getstr 的 (ncurses) 手册页说

Characters input are echoed only if echo is currently on. In that case, backspace is echoed as deletion of the previous character (typically a left motion).

在这种情况下,您可以(取决于您的 windows 的组织方式)使用 wattrset:

Set the “background” set of attributes to attr. This set is initially 0 (no attributes).

"background" 指的是 window 属性,这些属性与添加到 window 的文本关联的属性合并。由于 getstr 在它添加的文本中没有任何属性,设置 window 属性 "fixes" 是你的问题。但请记住,您需要保存原始属性以便在 getstr 完成后恢复它们。

ncurses curs_attr manual page explains this. The getstr 函数在内部使用 waddchprintwaddstr 也是如此),但它的手册页没有提及。