在Windows cmd中以彩色显示用户输入的文本 [英] display the user input text in color in the windows cmd

查看:113
本文介绍了在Windows cmd中以彩色显示用户输入的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于Windows cmd的小控制台程序,我还有另一个问题.

I have yet another question regarding my little console program for the windows cmd.

我使用colorama在终端中为文本着色,这看起来像这样:

I use colorama to color my text in the terminal which makes it look like this:

然后,我发现了如何使用一个带有打印但没有换行符的小"hack"来为 input()-方法中的文本着色,如下所示:

Then I found out how to color the text in an input()-method using a little "hack" with a print without linebreak, like this:

from colorama import init
init(autoreset=True)
YELLOW = "\x1b[1;33;40m" 

print(f"\n{YELLOW}Turnier spielen? [T]: ", end='')
tournament = input()

这将导致上图中的黄线.

this leads to the yellow line in the picture above.

但是我仍然在寻找一种为用户输入的字符上色的方法-所以在这里我也想用彩色来格式化用户输入的"sdffdgf ...".

But I still look for a way to color the very characters the user inputs - so here I would like to format the user input "sdffdgf..." in color as well.

有人对我有解决方案吗?或者有限的Windows cmd不可能吗?

has anyone a solution for me or will it just not be possible with the limited windows cmd?

推荐答案

从代码中删除 init(autoreset = True)行的操作在您的计算机上如您所愿.

Removing the init(autoreset=True) line from your code runs as you wish on my machine.

import colorama

from colorama import Fore,Style,Back
colorama.init()

YELLOW = "\x1b[1;33;40m" 
RED = "\x1b[1;31;40m"

print(f"\n{YELLOW}Turnier spielen? [T]: ", end='')
tournament = input()
print(f"\n{RED}Turnier spielen? [T]: ", end='')
tournament2 = input()

我的colorama版本 colorama == 0.3.9 .

My colorama version colorama==0.3.9.

Colorama文档指出,在使用 autoreset = true 时,会在 print 命令之后立即重置您的颜色和样式选项,这是在您进入输入命令之前发生的,这就是为什么您无法在用户键入的文本中获得颜色的原因.

The Colorama docs state that when using autoreset=true it will reset your colour and styling options immediately after the print command, this happens before you get to your input command which is why you do not get the colours in the user typed text.

这篇关于在Windows cmd中以彩色显示用户输入的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆