Python:如何将Tkinter文本标签与信息关联并在事件中访问它们?

2 投票
1 回答
688 浏览
提问于 2025-04-18 09:15

我在使用tkinter中的文本组件,并且给它加了一些标签,像这样:

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

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

简单来说,所有包含错误的文本都被标记为“err”。现在我想获取与鼠标悬停的标签相关的错误信息,但我不知道怎么知道哪个标签被悬停了。

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

如果我能提取到悬停标签的范围,那就解决了。有没有什么办法可以做到这一点?

1 个回答

4

这个 Motion event 事件有一些属性,其中一个就是鼠标的 x 和 y 坐标。Text 这个小部件可以把这些坐标当作索引来理解,所以你可以用 tag_prevrange 方法获取离鼠标位置最近的标签实例。

下面是一个例子:

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()

如果两个标签紧挨着,使用 tag_prevrange 方法可能会得到不想要的结果,因为它会找到标签的末尾,而不会有自然的分隔。不过,这个问题可能取决于你是如何在 Text 小部件中插入内容的。

撰写回答