简体   繁体   中英

How to make different word with different colour tkinter python?

I am making UI with Tkinter and stuck a little bit with coloring words. Goal is to make first word with red foreground second word with yellow foreground and do the same with next line of words:

Word_A (foreground red) Word_B (foreground yellow)

Word_CCC (foreground red) Word_DDD (foreground yellow)

Every word in my real program is different length (as the same in this example).

My Code:

 class Window(Frame):
    def __init__(self, master=None):
    Frame.__init__(self, master)
    self.master = master


    S = Scrollbar(self.master)
    T = Text(self.master, height=40, width=100)
    S.pack(side=RIGHT, fill=Y)
    T.pack(side=RIGHT, fill=X, expand=True)
    S.config(command=T.yview)
    T.config(yscrollcommand=S.set)


    for w in [('Word_A', 'Word_B'), ('Word_CCC', 'Word_DDD')]:


        T.insert(INSERT, w[0])
        T.insert(END, "  ")

        T.tag_add("start", "1.0", "1.5")
        T.tag_config("start", foreground="red")

        T.insert(END, w[1])
        T.insert(END, "\n")

        T.tag_add("here", "1.5", "10.0")
        T.tag_config("here", foreground="yellow")


top = Tk()
top.geometry('1000x1000')
app = Window(top)

top.mainloop()

You can directly add the tag to the word when you insert it: text.insert(<index>, <word>, <tag>) .

Here is an example:

import tkinter as tk

words = [('Word_A', 'Word_B'), ('Word_CCC', 'Word_DDD')]

root = tk.Tk()
text = tk.Text(root)
text.pack()
text.tag_configure('red', foreground='red')
text.tag_configure('yellow', foreground='yellow')

for w1, w2 in words:
    text.insert('end', w1, 'red')
    text.insert('end', ' ')
    text.insert('end', w2, 'yellow')
    text.insert('end', '\n')

root.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