2014-12-06 65 views
1

我目前使用python 2.7和我有麻烦一点点编码这个想法我有打字机效果。我知道很容易在python 2.7中使用colorama或termcolor之类的库对终端中的文本进行着色,但这些方法在我尝试使用的方式中并不起作用。彩色化终端文本可以用Python

你看,我想创建一个基于文本的冒险游戏,不仅具有彩色文本,但这样做的时候还给出了一个快速打字机式的效果。我有打字机效果,但随时尝试将它与彩色库集成,代码失败,给我原始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.") 

我很想在我的代码的任何反馈/改进,我真的想找到一种方法来调用t打印功能中的富勒库,而不会造成ASCII错误。

回答

1

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


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

在你的解决方法中,你只是打印什么也没有(即'')为红色,那么默认情况下,你打印的下一个文本也是红色的。接下来的所有文字都会显示为红色,直到您的颜色(或退出)为止Fore.RESET

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

这里有一个类似的例子,前挂起Fore.RED和发送到您的tprint()函数之前附加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 

这是我对堆栈的第一个答案,所以我没有张贴我的终端窗口输出的图像所需的口碑。

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