如何在Python中将彩色文本输出到终端?


当前回答

对于Windows,除非使用Win32 API,否则无法使用颜色打印到控制台。

对于Linux,它就像使用打印一样简单,转义序列如下:

颜色

要使字符像方框一样打印,这实际上取决于控制台窗口使用的字体。磅符号效果很好,但它取决于字体:

#

其他回答

如果你正在编程一个游戏,也许你想改变背景颜色,只使用空格?例如:

print " "+ "\033[01;41m" + " " +"\033[01;46m"  + "  " + "\033[01;42m"

根据乔尔德的回答,这简直太简单了:

class PrintInColor:
    RED = '\033[91m'
    GREEN = '\033[92m'
    YELLOW = '\033[93m'
    LIGHT_PURPLE = '\033[94m'
    PURPLE = '\033[95m'
    END = '\033[0m'

    @classmethod
    def red(cls, s, **kwargs):
        print(cls.RED + s + cls.END, **kwargs)

    @classmethod
    def green(cls, s, **kwargs):
        print(cls.GREEN + s + cls.END, **kwargs)

    @classmethod
    def yellow(cls, s, **kwargs):
        print(cls.YELLOW + s + cls.END, **kwargs)

    @classmethod
    def lightPurple(cls, s, **kwargs):
        print(cls.LIGHT_PURPLE + s + cls.END, **kwargs)

    @classmethod
    def purple(cls, s, **kwargs):
        print(cls.PURPLE + s + cls.END, **kwargs)

那么就

PrintInColor.red('hello', end=' ')
PrintInColor.green('world')

在windows 10中,您可以尝试使用这个小脚本,它用作颜色混合器,红色、绿色和蓝色的值为0-255:

import os

os.system('')


def RGB(red=None, green=None, blue=None,bg=False):
    if(bg==False and red!=None and green!=None and blue!=None):
        return f'\u001b[38;2;{red};{green};{blue}m'
    elif(bg==True and red!=None and green!=None and blue!=None):
        return f'\u001b[48;2;{red};{green};{blue}m'
    elif(red==None and green==None and blue==None):
        return '\u001b[0m'

并调用RGB函数使颜色的任意组合为:

g0 = RGB()
g1 = RGB(0,255,0)
g2 = RGB(0,100,0,True)+""+RGB(100,255,100)
g3 = RGB(0,255,0,True)+""+RGB(0,50,0)

print(f"{g1}green1{g0}")
print(f"{g2}green2{g0}")
print(f"{g3}green3{g0}")

不带参数的RGB()将清理并将前景/背景颜色设置为默认值。如果您想要黑色,则应将其称为RGB(0,0,0),白色RGB(255255255)。当RGB(0255,0)创建绝对绿色时,RGB(150255150)将生成浅绿色。

这支持背景色和前景色,要将颜色设置为背景色,必须使用bg=True传递,默认情况下为False。

例如:若要将红色设置为背景色,应将其称为RGB(255,0,0,True),但若要选择红色作为字体颜色,则只需将其命名为RGB(255,0,0,False),因为默认情况下bg为False,这将简化为仅将其称之为RGB(25.5,0,0)

使用pyfancy。这是一种在终端中进行颜色处理的简单方法!

例子:

print(pyfancy.RED + "Hello Red" + pyfancy.END)

还有Python termcolor模块。用法很简单:

from termcolor import colored

print colored('hello', 'red'), colored('world', 'green')

或者在Python 3中:

print(colored('hello', 'red'), colored('world', 'green'))

然而,对于游戏编程和你想做的“彩色方块”来说,它可能不够复杂。。。

要使ANSI代码在windows上运行,请首先运行

os.system('color')