【问题标题】:Colorize Terminal Text with Typewriter effect in Python在 Python 中使用打字机效果为终端文本着色
【发布时间】:2014-12-06 20:53:03
【问题描述】:

我目前使用的是 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 错误。

【问题讨论】:

    标签: python-2.7 terminal colorama


    【解决方案1】:

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


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

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

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

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

    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 有更多有用的示例和解释。希望我没有错过太多,祝你好运!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-04
      • 1970-01-01
      • 1970-01-01
      • 2012-11-21
      相关资源
      最近更新 更多