0

I want to redirect output to a ScrolledText wigget in a tkinter environment, and use the print function to display strings with colors in the widget.

My code prints the same string to the terminal and to the ScrolledText widget, using ANSI escape character (here for violet). It prints correctly in violet on the terminal, but does not print in color on the widget. Here is my code:

from tkinter import *
from tkinter import scrolledtext
import sys

# redirection of output to ScrolledText widget
def redir(inputStr):
    Twidg.insert(INSERT, inputStr)
    Twidg.yview(END)

fen = Tk()
fen.geometry('100x100+50+50')
fenpr = Toplevel(fen)
fenpr.geometry('200x100+200+50')
# creation of ScrolledText widget
Twidg = scrolledtext.ScrolledText(fenpr,wrap = WORD, \
                              height=20, width = 40)
Twidg.focus()
Twidg.place(x=10,y=10)
# printing color on terminal
print('\033[35mviolet')
print('\033[m')
# redirection of output
sys.stdout.write = redir
# printing color on ScrolledText widget
# no color appears 
print('\033[35mviolet')
fen.mainloop()
2
  • 1
    GUI widgets usually set colors based on object attributes. ANSI escape sequences are only relevant to windows that emulate old style ANSI terminals, such as command windows. Commented May 19 at 14:27
  • 1
    Basically no. However you can parse the string for ANSI color code and use ttk styling to color the message. Commented May 20 at 15:32

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.