我知道可以像这样打印 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/