我在 tkinter 中使用文本小部件,并与它关联了一些标签,如下所示:
textw.tag_config( "err", background="pink" );
textw.tag_bind("err", '<Motion>', self.HoverError);
基本上所有包含错误的文本都带有“err”标记。现在我想访问与悬停标签相关的错误消息,但我不知道如何知道悬停的是哪个标签。
def HoverError( self, event ):
# Get error information
如果我可以提取悬停标签的范围,问题就可以解决。我有什么想法可以实现这一点吗?
最佳答案
Motion
事件
具有与其关联的属性,其中之一是鼠标的 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
小部件,这可能不是问题。
关于Python:如何将 Tkinter 文本标签与信息关联并在事件中访问它们?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24135629/