我是 Python 和 StackOverflow 的新手,需要一点帮助。我想用 Python 打印颜色并用谷歌搜索但运气不佳 :( 我每次都感到困惑,但没有一个有效。 这是我输入的代码。
answer = input ("Wanna go explore? OPTIONS : Yes or No")
if answer == "no":
print("Awww, come on, don't be like that, lets go!")
elif answer == "yes":
print ("Great! Lets go!")
else:
print("Whats that? I couldn't hear you!")
现在,我想让 OPTIONS 为绿色,Yes 为蓝色,No 为红色。如何实现这一目标?
最佳答案
如果您想在 IDLE shell 中打印颜色,则使用 ASCI 转义码的答案对您没有帮助,因为它没有实现此功能。
有一个特定于 IDLE 的 hack,它允许您直接写入它的 PyShell
对象并指定 IDLE 已经定义的文本标记,例如将出现的 "STRING"
默认为绿色。
import sys
try:
shell = sys.stdout.shell
except AttributeError:
raise RuntimeError("you must run this program in IDLE")
shell.write("Wanna go explore? ","KEYWORD")
shell.write("OPTIONS","STRING")
shell.write(" : ","KEYWORD")
shell.write("Yes","DEFINITION")
shell.write(" or ","KEYWORD")
shell.write("No","COMMENT")
answer = input()
在 IDLE 中运行时将导致此提示:
这里是所有可用标签的列表:
print("here are all the valid tags:\n")
valid_tags = ('SYNC', 'stdin', 'BUILTIN', 'STRING', 'console', 'COMMENT', 'stdout',
'TODO','stderr', 'hit', 'DEFINITION', 'KEYWORD', 'ERROR', 'sel')
for tag in valid_tags:
shell.write(tag+"\n",tag)
请注意,'sel'
的特殊之处在于它代表被选中的文本,因此一旦单击其他内容,它就会取消选中。它也可以用来开始一些选择用于复制的文本。
关于python - 如何在 python 中打印颜色/颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11108559/