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
348 views
in Technique[技术] by (71.8m points)

python - How do I print colored text in IDLE's terminal?

This is very easily a duplicate question--because it is. However, there are very many inadequate answers to this (e.g. try curses! -- pointing to a 26 page documentation).

I just want to print text in a color other than blue when I'm outputting in IDLE. Is it possible? What's an easy way to do this? I'm running Python 3.6 on Windows.

Please explain with an example.

(I have found that ANSI codes do not work inside IDLE, only on the terminal.)

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Put this at the "start" of your code:

import sys

try:
    color = sys.stdout.shell
except AttributeError:
    raise RuntimeError("Use IDLE")

And then use color.write(YourText,Color) for "printing":

color.write("Hi, are you called Miharu461? 
","KEYWORD")
color.write("Yes","STRING")
color.write(" or ","KEYWORD")
color.write("No
","COMMENT")

This prints:

Prints


Note: this does NOT automatically puts the enter (like in the print function/statement). So, when you are printing put at the end of the last string to put it.

The "Colors" you can put are: SYNC, stdin, BUILTIN, STRING, console, COMMENT, stdout, TODO, stderr, hit, DEFINITION, KEYWORD, ERROR, and sel.

Note 2: This is dependent of the color scheme you are using for IDLE. So I recommend you to use it for highlighting, and not for making a program for asking what in color is some word.


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

1.4m articles

1.4m replys

5 comments

56.9k users

...