Search code examples
pythontkintertkinter-text

Can I insert a string into a tkinter text box with a tag?


I would like to insert text into my console text box in tkinter, but I would like to insert the text with a tag, instead of setting a tag afterwards. Is this possible? If not is there a better way to do this than what I am already doing?

I tried this:

console.config(state="normal")
start = output.index(END)
console.insert(END, string)
end = output.index(END)
console.tag_add("err", start, end)
console.config(state="disabled")

But it did not completely work the way I wanted it to. It highlighted more text than I wanted with the err tag.


Solution

  • The insert method accepts both text and tags. The first argument after the index is text to insert, the next argument is assumed to be a tag, the next is text, the next is a tag, etc.

    The following example will insert the string at the end of the widget, and add the tag err to the inserted text.

    console.insert(END, string, "err")
    

    You can provide a single tag, or multiple tags in a tuple. The following example inserts text with the tags err and critical:

    console.insert(END, string, ("err", "critical"))
    

    The following example shows how you can insert multiple strings and multiple sets of tags in a single call to insert. It will insert the string "foobar", with "foo" getting the tag red and "bar" getting the tag green.

    console.insert(END, "foo", "red", "bar", "green")