gpt4 book ai didi

python - 打印 RGB 背景

转载 作者:行者123 更新时间:2023-12-05 09:29:40 26 4
gpt4 key购买 nike

我知道可以像这样打印 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-graphicsSelect 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的转义序列就可以了一个将前景色和背景色都重置为它们的颜色默认。

关于python - 打印 RGB 背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70519979/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com