简体   繁体   中英

How can I set some text color in a tkinter text widget

can someone tell me how can I change color to certain parts of a tkinter text widget. This is a simple view of my code (it's a chat so it has to display who sent the message):

T = Text(window, bg="black", fg="white", font=("bold", 12))

def addMessage(text)
    T.insert("me: ")
    T.insert(text+"\n")

addMessage("hi")

how can I set the "me: " part to be blue and the text part to stay white?

Try this:

from tkinter import *
window = Tk()

T = Text(window, bg="black", fg="white", font=("bold", 12))
# Create a tag named "blue" and set the color of it to blue
T.tag_config("blue", foreground="blue")
T.grid()

def addMessage(text):
    # apply the tag while inserting
    T.insert(END, "me: ", "blue")
    T.insert(END, text+"\n")

addMessage("hi")

window.mainloop()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM