【问题标题】:Change color of individual print line in Python 3.2? [duplicate]在 Python 3.2 中更改单个打印行的颜色? [复制]
【发布时间】:2011-08-18 22:13:57
【问题描述】:

我正在学习 Python 3.2 以进行基于文本的小冒险,以便练习并更加熟悉该语言。无论如何,我想让它在某些动作发生时,打印文本的颜色会发生变化。我该怎么做。

例如,我希望出现的第一个文本是:

if 'strength' in uniqueskill.lower():
time.sleep(3)
print('As you are a Warrior, I shall supply you with the most basic tools every Warrior needs.')
time.sleep(3)
print('A sword and shield.')
time.sleep(1)
print('You have gained A SWORD AND SHIELD!')

【问题讨论】:

标签: python printing colors


【解决方案1】:

Colorama 是一个很棒的完全跨平台的模块,可以用不同的颜色打印到终端/命令行。

示例:

import colorama
from colorama import Fore, Back, Style

colorama.init()

text = "The quick brown fox jumps over the lazy dog"

print(Fore.RED + text)
print(Back.GREEN + text + Style.RESET_ALL)
print(text)

给你:

【讨论】:

  • 不断收到 AssertionError。
  • 编辑为使用 Python3 打印语句。您仍然收到错误吗?如果是这样,请将您正在运行的代码和完整的堆栈跟踪粘贴到某处。
  • 还是报错,代码如下: import colorama from colorama import Fore, Back, Style colorama.init() notesaction = "You have got a SWORD AND SHIELD!" if 'strength' in uniqueskill.lower(): time.sleep(3) print('既然你是战士,我会为你提供每个战士需要的最基本的工具。') time.sleep(3) print('剑和盾。') time.sleep(1) print(Fore.RED + noteaction)
  • 我发现问题在于您使用的是 IDLE:stackoverflow.com/questions/5902233/…
  • 在windows中很好用,谢谢
【解决方案2】:

您没有指定您的平台,这在这里非常重要,因为将彩色文本输出到控制台的大多数方法都是特定于平台的。例如,Python 附带的 curses 库仅适用于 UNIX,而 ANSI 代码不再适用于新版本的 Windows。我能想到的最跨平台的解决方案,就是在Windows机器上安装Windows version of curses并使用它。

下面是一个使用curses颜色的例子:

import curses

# initialize curses
stdscr = curses.initscr()
curses.start_color()

# initialize color #1 to Blue with Cyan background
curses.init_pair(1, curses.COLOR_BLUE, curses.COLOR_CYAN)

stdscr.addstr('A sword and a shield.', curses.color_pair(1))
stdscr.refresh()

# finalize curses
curses.endwin()

请注意,curses 比只有颜色更复杂。您可以使用它在控制台屏幕上定义多个窗口、使用绝对或相对坐标定位文本、操作键盘输入等等。你可以在这里找到一个教程: http://docs.python.org/dev/howto/curses.html

【讨论】:

  • 我在 Windows 7 上,最终弄明白了。我安装了 Colorama 库并使用了代码:print('\x1b[34m' + 'YOU HAVE GAINED A SWORD AND SHIELD!')。问题是最终的结果是“34mYOU HAVE A SWORD AND SHIELD!”但它是正确的颜色。有什么办法可以隐藏字母和数字?
  • @Crashdown - 示例在发布时被剪切,阅读编辑。
  • 我更喜欢使用 curses 而不是普通的 ANSI 代码,原因有两个:它们很难看(尤其是当您与测试混合时),并且 curses 更强大。无论如何,我不知道如何让它们在 Windows 上的 python 中正常工作,我不会打扰。如果我需要一个仅限 Windows 的实现,我会使用 WConioconsole
  • 你必须自己编译它们,因为它们似乎没有 python 3.2 版本。
  • @Boaz:请参阅我的回答,了解如何使用 colorama。
猜你喜欢
  • 2021-07-14
  • 2013-11-12
  • 2017-02-11
  • 1970-01-01
  • 1970-01-01
  • 2014-05-18
  • 2017-07-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多