You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python 3.10中Curses无法正常使用全范围颜色对的问题

Python curses库无法使用全范围颜色对的问题

我运行Python 3.10,使用curses库时遇到颜色对相关问题,无法利用全范围的颜色对。

相关检测结果:

  • curses.COLORS返回256
  • curses.COLOR_PAIRS返回65536
  • curses.has_extended_color_support()返回True

但实际使用中存在以下问题:

  • 初始化ID为256、512、768、1024这类数值的颜色对时,会重置已初始化的颜色。
  • 尝试显示ID大于255(即curses.COLORS - 1)的颜色对时,系统会自动使用ID小于255的颜色对替代,而非我设置的对应ID。调用init_pair时curses允许使用这些ID,但完全忽略设置,直接复用ID小于255的颜色对效果。

示例代码

#!/usr/bin/env python3.10

"""
Python3.10 added extended color support to curses
curses.COLORS (xterm-256color) returns 256
curses.COLOR_PAIRS (xterm-256color) returns 65,536
"""

import curses


def cycler(start_color, end_color):
    # cycle through all possible color IDs or pair IDs curses can display, loops indefinitely
    while True:
        for i in range(start_color, end_color):
            yield i


def main(stdscr):
    curses.start_color()
    height, width = stdscr.getmaxyx()

    RED = 1  # Reserve the red color at color ID 1
    curses.init_color(RED, 1000, 0, 0)

    color_cycler = cycler(2, curses.COLORS - 1)  # RED is reserved at 1, start at 2
    pair_cycler = cycler(1, curses.COLOR_PAIRS - 1)

    has_extended_support = curses.has_extended_color_support()
    stdscr.addstr(0, 0, f"COLORS:{curses.COLORS} "
                        f"COLOR_PAIRS:{curses.COLOR_PAIRS} "
                        f"ExtendedSupport:{has_extended_support}", curses.color_pair(1))

    for y in range(1, height - 1):
        for x in range(0, width, 5):

            color_id = next(color_cycler)
            pair_id = next(pair_cycler)

            intensity = int((color_id / (curses.COLORS - 1)) * 1000)
            curses.init_color(color_id, intensity, intensity, intensity)

            # create a new color pair, (RED) foreground, (color) background
            curses.init_pair(pair_id, RED, color_id)
            string = str(pair_id).rjust(5, ' ')
            stdscr.addstr(y, x, string, curses.color_pair(pair_id))

    stdscr.noutrefresh()
    curses.doupdate()
    stdscr.getch()


if __name__ == "__main__":
    curses.wrapper(main)

运行截图

运行代码后生成的截图(注意图中的数字256、512、768、1024,这些是对应的颜色对ID):
运行截图

测试过的终端应用

  • gnome-terminal
  • terminology
  • tilda

所有终端均存在相同问题。

内容的提问来源于stack exchange,提问作者Daniel Griffin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 07:05:20