【问题标题】:Changing background color and color of text更改背景颜色和文本颜色
【发布时间】:2018-12-25 19:14:05
【问题描述】:

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

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 这样的新窗口中。

【问题讨论】:

  • 不是重复的,我不知道如何根据列表中的项目更改颜色
  • 你想在新窗口中(例如 pygame、pyglet)还是在控制台中?
  • 我想要在控制台中
  • @J.Doe 你可以使用亚历克斯的建议......它就在那里,至少有 57 票赞成如何用颜色打印,实际上和背景

标签: python python-3.x colors


【解决方案1】:

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

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])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-31
    • 2011-01-29
    相关资源
    最近更新 更多