python - 打印 RGB 背景

我知道可以像这样打印 RGB 彩色文本:

def colored(r, g, b, text):
    return "\033[38;2;{};{};{}m{} \033[39m".format(r, g, b, text)


text = "Hello, World"
colored_text = colored(132, 204, 247, text)
print(colored_text)

但是,有没有办法用 RGB 彩色背景打印?

因为,据我所知,有几种用于打印的内置背景色。但我希望能够使用 rgb 代码并为打印的文本获得合适的背景颜色。

这可能吗?

谢谢。

最佳答案

根据 https://chrisyeh96.github.io/2020/03/28/terminal-colors.html#ansi-escape-codes-for-terminal-graphics Select Graphic Rendition 参数在 '\033[' 之后( Control Sequence Inducer)用于定义背景颜色 是 48;2;r;g;b

所以这里是 colored_background 返回文本参数 给定的背景颜色:

def colored_background(r, g, b, text):
    return f'\033[48;2;{r};{g};{b}m{text}\033[0m'

text = "What a nice red background!"
colored_text = colored_background(255, 0, 0, text)
print(colored_text)

你可以自然地将两者结合起来:

def colored(fg_color, bg_color, text):
    r, g, b = fg_color
    result = f'\033[38;2;{r};{g};{b}m{text}'
    r, g, b = bg_color
    result = f'\033[48;2;{r};{g};{b}m{result}\033[0m'
    return result

text = "What a nice blue text with a red background!"
colored_text = colored((0, 0, 255), (255, 0, 0), text)
print(colored_text)

注意这里只需要一个参数为0的转义序列就可以了 一个将前景色和背景色都重置为它们的颜色 默认。

https://stackoverflow.com/questions/70519979/

相关文章:

node.js - 带有 Webpack 的 Electron 原生 NodeJS 模块

c++ - 即使在手动设置显示环境变量后,WSL Ubuntu 仍显示 "Error: Unable

javascript - 一键执行两个功能

python - 如何解析 (1045, "Access denied for user ' Use

haskell - 如何为自定义数据类型定义 (+) 函数?

() takes ">python - 为什么在我给出位置参数时 lambda 返回 "() takes

r - 在 R 中查找汇总列的相对频率

r - 是否可以将变量从全局环境移动到单独的环境中?

c# - Entity Framework 排序列表

c++ - 使用 C++ 生成真正的随机数 (Windows 10 x64)