【问题标题】:How do I make python 3.7 print out colored text?如何让 python 3.7 打印出彩色文本?
【发布时间】:2019-03-22 11:29:06
【问题描述】:

我是一个整体编程新手,但是我已经能够用 python 编写一个基本的游戏。我无法在 Windows 10 上的 powershell 中打印彩色文本,它是 cmd,或者在 Python 附带的 IDLE 中。虽然它不会使我的代码崩溃,但我希望我的游戏能够打印出彩色文本,所以我需要创建一个可以做到这一点的方法。

def ColorText(text, color):
  CEND      = '\033[0m'
  CBOLD     = '\033[1m'
  CRED    = '\033[91m'
  CGREEN  = '\033[32m'
  CYELLOW = '\033[33m'
  CBLUE   = '\033[34m'
  CVIOLET = '\033[35m'
  CBEIGE  = '\033[36m'
  if color == 'red':
      return CRED + CBOLD + text + CEND
  elif color == 'green':
      return CGREEN + CBOLD + text + CEND
  elif color == 'yellow':
      return CYELLOW + CBOLD + text + CEND
  elif color == 'blue':
      return CBLUE + CBOLD + text + CEND
  elif color == 'voilet':
      return CVIOLET + CBOLD + text + CEND
  elif color == 'beige':
      return CBEIGE + CBOLD + text + CEND

【问题讨论】:

  • 你确定你的终端模拟器支持着色吗? cmd 非常简单。
  • 我不确定它是否支持颜色,但是如果它正确解释代码,我会假设它不会打印出一个未知字符后跟字符串。

标签: python text printing colors


【解决方案1】:

Color_Console 库相对更易于使用。 安装这个库,下面的代码会帮助你。

from Color_Console import *
ctext("This will be printed" , "white" , "blue")

第一个参数是要打印的字符串, 第二个参数是文本的颜色 最后一个是背景色。

最新版本的 Color_Console 允许您传递颜色列表或字典,这些颜色会在指定的延迟时间后发生变化。

此外,他们对所有功能都有很好的文档。

访问https://pypi.org/project/Color-Console/了解更多。

【讨论】:

    【解决方案2】:

    colorprint 可以帮忙。

    pip install color
    
    from colorprint.printer import uprint
    from colorprint.unicolor import *
    uprint("FOREGROUND_GREEN\n", fore=FOREGROUND_GREEN)
    uprint("BACKGROUND_WHITE\n", back=BACKGROUND_WHITE)
    

    此存储库支持尽可能多的终端支持。

    https://github.com/sailist/colorprint

    【讨论】:

      【解决方案3】:

      您也可以使用clrprint 模块,它也适用于空闲、终端和PowerShell

      pip install clrprint
      

      然后使用它:

      from clrprint import *
      clrhelp() # print's available colors and usage
      
      user_input = clrinput("input please: ",clr='r') # just like input() [color is red]
      clrprint('your text',user_input,clr='green') # just like print() 
      

      【讨论】:

        【解决方案4】:

        您可以像这样在 windows cmd 中打印出彩色文本(更改整个 cmd 的颜色):

        import os
        os.system("color 3") # colour can be any number between 1 to 8
        print("Your text")
        

        或者你可以像这样使用colorama

        from colorama import init, Fore, Back, Style
        init(convert=True)
        print(Fore.RED + 'some red text') 
        print(Back.GREEN + 'and with a green background') 
        print(Style.DIM + 'and in dim text') 
        print(Style.RESET_ALL) 
        print('back to normal now') 
        

        您可以阅读 GeeksForGeeks 上的这篇文章,该文章展示了如何在终端中更改颜色:https://www.geeksforgeeks.org/print-colors-python-terminal/

        【讨论】:

        • 谢谢,但我需要改变一个单词或句子的颜色,而不是整个命令。您是否知道任何其他操作系统指挥官可能会这样做但规模较小?
        猜你喜欢
        • 2023-04-06
        • 1970-01-01
        • 2023-03-08
        • 1970-01-01
        • 2010-09-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多