简体   繁体   中英

Python: How do I associate Tkinter text tags with information and access them in an event?

I am using a Text widget in tkinter and have associated some tags with it like this:

textw.tag_config( "err", background="pink" );

textw.tag_bind("err", '<Motion>', self.HoverError);

Basically all the text that contains an error is tagged with "err". Now I want to access the associated error message with the hovered tag but I don't know how to know which tag was hovered.

def HoverError( self, event ):
   # Get error information

If I could just extract the range of the hovered tag it would be solved. Any ideas of how I can accomplish this?

The Motion event has attributes associated with it, and one of those is the x, y coordinates of the mouse. The Text widget can interpret those coordinates as indices, so you can grab the instance of the tag nearest the index where the mouse is using the tag_prevrange method.

Here's an example:

def hover_over(event):

    # get the index of the mouse cursor from the event.x and y attributes
    xy = '@{0},{1}'.format(event.x, event.y)

    # find the range of the tag nearest the index
    tag_range = text.tag_prevrange('err', xy)

    # use the get method to display the results of the index range
    print(text.get(*tag_range))


root = Tk()

text = Text(root)
text.pack()

text.insert(1.0, 'This is the first error message ', 'err')
text.insert(END, 'This is a non-error message ')
text.insert(END, 'This is the second error message ', 'err')
text.insert(END, 'This is a non-error message ')
text.insert(END, 'This is the third error message', 'err')

text.tag_config('err', background='pink')
text.tag_bind('err', '<Enter>', hover_over)

root.mainloop()

The tag_prevrange method will give you unwanted results if two tags bump up against each other (it will seek to the end of the tag, as there won't be a natural break), but depending on how you insert into the Text widget, this may not be an issue.

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