如何在Python 3.2中改变单独打印行的颜色?

9 投票
2 回答
70021 浏览
提问于 2025-04-16 17:01

我正在用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!')

2 个回答

6

你没有说明你使用的平台,这一点很重要,因为大多数在控制台输出彩色文本的方法都是针对特定平台的。例如,Python自带的curses库只适用于UNIX系统,而ANSI代码在新版本的Windows上已经不再有效。我能想到的最通用的解决方案是,在Windows电脑上安装curses的Windows版本并使用它。

下面是一个使用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

32

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)

这样做会得到:

enter image description here

撰写回答