我在tkinter中使用了文本小部件,并已将一些标签与之关联:
textw.tag_config( "err", background="pink" );
textw.tag_bind("err", '<Motion>', self.HoverError);
基本上所有包含错误的文本都用“ err”标记。现在,我想使用悬停的标签访问相关的错误消息,但是我不知道如何知道悬停了哪个标签。
def HoverError( self, event ):
# Get error information
如果我可以提取悬停标签的范围,则可以解决。关于如何实现此目标的任何想法?
的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
窗口小部件的方式,此方法可能不会成为一个问题。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句