100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > python打字机效果_使用Python中的打字机效果为终端文本着色

python打字机效果_使用Python中的打字机效果为终端文本着色

时间:2019-07-23 06:05:18

相关推荐

python打字机效果_使用Python中的打字机效果为终端文本着色

我目前正在使用python 2.7,并且在编码这个想法时遇到了一些麻烦。我知道使用colorama或termcolor之类的库在python 2.7中的终端中为文本着色很容易,但是这些方法在我尝试使用的方式中并不起作用。

您会发现,我正在尝试创建一个基于文本的冒险游戏,该游戏不仅具有彩色文本,而且在这样做时还具有快速打字机风格的效果。我的打字机效果下降了,但是任何时候我尝试将其与着色库集成时,代码都会失败,从而给我原始的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错误的方法。

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

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

在您的解决方法中,您仅以红色不打印任何内容(即''),然后默认情况下您要打印的下一个文本也为红色。直到您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

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

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。