在Python中使用打字机效果着色终端文本

时间:2014-12-06 20:53:03

标签: python-2.7 terminal colorama

我目前正在使用python 2.7,我在编写这个想法时遇到了一些麻烦。我知道在python 2.7的终端中使用colorama或termcolor等库来为文本添加颜色很容易,但是这些方法并没有像我想要的那样工作。

你知道,我正在尝试创建一个基于文本的冒险游戏,它不仅具有彩色文本,而且在这样做时也提供了快速的打字机式效果。我有打字机效果,但是当我尝试将它与色彩库集成时代码失败,给我原始的ASCII字符而不是实际的颜色。

import sys
from time import sleep
from colorama import init, Fore
init()

def tprint(words):
for char in words:
    sleep(0.015)
    sys.stdout.write(char)
    sys.stdout.flush()

tprint(Fore.RED = "This is just a color test.")

如果您运行代码,您将看到打字机效果有效,但颜色效果却没有。有没有什么方法可以将颜色“嵌入”到文本中,以便sys.stdout.write会用它显示颜色?

谢谢

修改

我想我可能找到了一种解决方法,但用这种方法改变单个单词的颜色有点痛苦。显然,如果在调用tprint函数之前使用colorama设置ASCII颜色,它将以最后设置的颜色打印。

以下是示例代码:

print(Fore.RED)
tprint("This is some example Text.")

我希望对我的代码有任何反馈/改进,因为我真的想找到一种方法在tprint函数中调用Fore库而不会导致ASCII错误。

1 个答案:

答案 0 :(得分:1)

TL; DR:在您的字符串前加上所需的Fore.COLOUR,不要忘记Fore.RESET


首先 - 酷打字机功能!

在您的解决方法中,您只是以红色打印 nothing (即''),然后默认情况下,您打印的下一个文本也是红色。随后的所有文本都将显示为红色,直到您Fore.RESET颜色(或退出)。

更好的(更多 pythonic ?)方式是直接明确构建您想要的颜色的字符串。

这是一个类似的示例,预先挂起Fore.RED并在发送到Fore.RESET函数之前将tprint()附加到字符串中:

import sys
from time import sleep
from colorama import init, Fore
init()


def tprint(words):
    for char in words:
        sleep(0.015)
        sys.stdout.write(char)
        sys.stdout.flush()

red_string = Fore.RED + "This is a red string\n" + Fore.RESET

tprint(red_string)    # prints red_string in red font with typewriter effect


为了简单起见,将tprint()功能放在一边,这种颜色键入方法也适用于字符串的连接:

from colorama import init, Fore
init()

red_fish = Fore.RED + 'red fish!' + Fore.RESET
blue_fish = Fore.BLUE + ' blue fish!' + Fore.RESET

print red_fish + blue_fish    # prints red, then blue, and resets to default colour

new_fish = red_fish + blue_fish    # concatenate the coloured strings

print new_fish    # prints red, then blue, and resets to default colour


更进一步 - 构建具有多种颜色的单个字符串:

from colorama import init, Fore
init()

rainbow = Fore.RED + 'red ' + Fore.YELLOW + 'yellow ' \
+ Fore.GREEN + 'green ' + Fore.BLUE + 'blue ' \
+ Fore.MAGENTA + 'magenta ' + Fore.RESET + 'and then back to default colour.'

print rainbow    # prints in each named colour then resets to default

这是我在Stack上的第一个答案,所以我没有发布终端窗口输出图像所需的声誉。

official colorama docs有更多有用的例子和解释。希望我没有错过太多,祝你好运!

相关问题