Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
703 views
in Technique[技术] by (71.8m points)

windows - How to print colour/color in python?

New to both Python and StackOverflow, I'd like a little help. I'd like to print color in Python and have Googled but with little luck :( I've been confused each time and none has worked. This is the code I have typed.

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!")

Now, I would like to have OPTIONS colored Green and Yes colored blue and No colored Red. How would one achieve this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you want to print color in the IDLE shell no answer using ASCI escape codes will help you as it does not implement this feature.

There is a hack specific to IDLE that lets you write to it's PyShell object directly and specify text tags that IDLE has already defined such as "STRING" which will appear as green by default.

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()

When run in IDLE will result in this prompt:

enter image description here

Here is a list of all valid tags for use:

print("here are all the valid tags:
")

valid_tags = ('SYNC', 'stdin', 'BUILTIN', 'STRING', 'console', 'COMMENT', 'stdout',
              'TODO','stderr', 'hit', 'DEFINITION', 'KEYWORD', 'ERROR', 'sel')

for tag in valid_tags:
    shell.write(tag+"
",tag)

Note that 'sel' is special that it represents the text that is selected, so it will be un-selected once something else is clicked on. As well it can be used to start some text selected for copying.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...