Jadon Erwin
Jadon Erwin

Reputation: 651

How do you get the tags from text in a Tkinter text widget?

I am struggling to find any documentation of how you get tags from text in a Tkinter text widget. The Canvas widget has a gettags() method. I would imagine the text widget has a similar method but I can't find anything.

How can I get a list of all tags used in a specific range of characters?

Upvotes: 0

Views: 1143

Answers (1)

Bryan Oakley
Bryan Oakley

Reputation: 385900

There is no command that can give you a list of tags for a range of characters, but there is a command to get the tags for a single character. If you want a list of all tags used anywhere in a range of characters you can iterate over the characters with something like this:

def get_tags(start, end):
    index = start
    tags = []
    while text.compare(index, "<=", end):
        tags.extend(text.tag_names(index))
        index = text.index(f"{index}+1c")

    return set(tags)

If you have a string that has character 1.0 tagged with "foo", and 1.1 is tagged as "bar", then `get_tags("1.0", "1.1") will return ("foo", "bar") since each tag was used somewhere in that range.

Upvotes: 3

Related Questions