1

我目前正在使用 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 错误的方法。

4

1 回答 1

1

TL;DR:在你的字符串前面加上想要的Fore.COLOUR,不要忘记Fore.RESET在最后。


首先——很酷的打字机功能!

在您的解决方法中,您只是不打印任何东西(即''),然后默认情况下您打印的下一个文本也是红色的。Fore.RESET在您选择颜色(或退出)之前,随后的所有文本都将显示为红色。

一个更好的(更Pythonic的?)方法是直接和明确地用你想要的颜色构建你的字符串。

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

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 上的第一个答案,因此我没有发布终端窗口输出图像所需的声誉。

官方的colorama 文档有更多有用的示例和解释。希望我没有错过太多,祝你好运!

于 2015-04-29T01:05:01.240 回答