3

i have some tags in a text widget and bound a click function to all of them.

My example sentence is "my cute, little cat". "Cute" and "little" are the tagged words with the tag adj.

In this click function i can not figure out the way to get the string i clicked. When i click on cute i want to print cute to the console.

This is what i have so far, i did not include how i apply the tag, since this works. The click function is called correctly.

    def __init__(self, master):
        # skipped some stuff here
        self.MT.tag_config('adj', foreground='orange')
        # here i bind the click function
        self.MT.tag_bind('adj', '<Button-1>', self.click)

    def click(self, event):
        print(dir(event))
        # i want to print the clicked tag text here

Is there a way to do this?

Best, Michael

1 Answer 1

6

I managed to extract the text of the clicked label from the cursor position. I converted it to an index and checked for the tag that covered the index.

Here is my solution:

    def click(self, event):
        # get the index of the mouse click
        index = self.MT.index("@%s,%s" % (event.x, event.y))

        # get the indices of all "adj" tags
        tag_indices = list(self.MT.tag_ranges('adj'))

        # iterate them pairwise (start and end index)
        for start, end in zip(tag_indices[0::2], tag_indices[1::2]):
            # check if the tag matches the mouse click index
            if self.MT.compare(start, '<=', index) and self.MT.compare(index, '<', end):
                # return string between tag start and end
                return (start, end, self.MT.get(start, end))
Sign up to request clarification or add additional context in comments.

1 Comment

Instead of using event.widget.tag_ranges('adj'), it might be better to use event.widget.tag_names(index). This will remove the need for the for loop and all of those event.widget.compare calls making the function much faster.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.