how would you go about highlighting text in the tkinter text widget ?

Recommended Answers

All 10 Replies

You could use a prompt.

prompt = ("TEST")
label1 = Label(root, text=prompt, width=len(prompt), bg='yellow')

is prompt just a variable ??

Yeah it is. Sorry the way I said that did make it sound like a function. Basically you can use bg='yellow' to set the background of the text to be yellow. I just used this today, so here is a picture of what is looks like when used in a Tkinter box. [IMG][/IMG]
By scott454 at 2012-02-18

i got a text in a text widget, how would highlight text that's in a tkinter text widget, i think you cant put lables ontop of a text widget ?

Here try this.

import Tkinter as tk

root = tk.Tk()
text = tk.Text(root, font=("Helvetica", 50))

text.insert(tk.END, "Hello, World")
#Designate what letters to highlight
#in this case Hello and W is highlighted
text.tag_add("Hello", "1.0", "1.5")
text.tag_add("W", "1.7", "1.8")
text.tag_config("Hello", background="yellow", foreground="blue")
text.tag_config("W", background="black", foreground="green")


thanks for your great example, can you please explain what does the numbers in the text.tag_add do, "1.0" "1.5" ?

1st line beginning 1st line 0th to 5th letter, I think. Same as "Hello, World"[0:5]

so for example if i wanted to highlight all the l in a text i would have to pick out each position ?

Vegaseat has a nice example in the "Python GUI Programming" sticky, but I refuse to be someone else's research assistant. If memory serves it is somewhere in the middle of the thread's pages.

it still doesnt work do you know where im going wrong ???

def highlight(seq):
    #remove highlights
    if "highlight" in Text.tag_names():

        i = len(seq)
        index = "1.0"
        while True:
            index =, index, nocase=1, stopindex='end')
            if index:
                index2 = Text.index("%s+%d" % (index, i))
                Text.tag_add("highlight", index, index2)
                Text.tag_config("highlight", background="yellow")
                index = index2
            else: return
button4 = ttk.Button(content,text="highlight", command=lambda:highlight("s"))
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.