Jac*_*ack 5 python printing colors
我正在研究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!')
Run Code Online (Sandbox Code Playgroud)
Aco*_*orn 30
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)
Run Code Online (Sandbox Code Playgroud)
给你:

你没有指定你的平台,这在这里非常重要,因为大多数输出颜色文本到控制台的方法都是特定于平台的.例如,Python附带的curses库只支持UNIX,ANSI代码不再适用于新版本的Windows.我能想到的最跨平台的解决方案是在Windows机器上安装Windows版本的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()
Run Code Online (Sandbox Code Playgroud)
请注意,curses比只有颜色更复杂.您可以使用它在控制台屏幕上定义几个窗口,使用绝对或相对坐标定位文本,操作键盘输入等.你可以在这里找到一个教程:http: //docs.python.org/dev/howto/curses.html