首页 > 解决方案 > 更改背景颜色和文本颜色

问题描述

假设我在列表中有几个数字:

listt = [2, 4, 6]

有什么方法可以改变每个数字的背景颜色和颜色,具体取决于它是哪个数字。例如:

for i in range(3):
    if listt[i] == 2:
        # make background color green and make number red
    elif listt[i] == 4:
        # make background color orange and make number green
    elif listt[i] == 6
        # make background color red and make number orange
    print(nlistt[i])

有什么办法可以做到这一点,如果没有背景和常规颜色,你可以做 2 个中的 1 个。这应该在控制台中,而不是在 pygame 之类的新窗口中。

标签: pythonpython-3.xcolors

解决方案


只需将颜色代码应用于您要打印的内容,颜色代码可以在@Alex Taylor提到的帖子中找到。

listt = [2, 4, 6]
nlistt = listt.copy()
for i in range(3):
    if listt[i] == 2:
        # make background color green and make number red
        nlistt[i] = '\033[1;31;42m' + str(nlistt[i]) + '\033[0m'
    elif listt[i] == 4:
        # make background color orange and make number green
        nlistt[i] = '\033[1;32;43m' + str(nlistt[i]) + '\033[0m'
    elif listt[i] == 6:
        # make background color red and make number orange
        nlistt[i] = '\033[1;33;41m' + str(nlistt[i]) + '\033[0m'
    print(nlistt[i])

推荐阅读