[Python] Is it possible to use ANSI escape characters for color printing in a ScrolledText...

Discussão em 'Python' iniciado por Stack, Maio 19, 2025.

  1. Stack

    Stack Membro Participativo

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

    Continue reading...

Compartilhe esta Página