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

标签 python tags tkinter

我在 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/

相关文章:

python - 将带有日期值的列表加载到 pandas 数据框中并随时间绘制事件图

javascript - 使用javascript获取标签的值

php 包含和结束标记

combobox - 如何将值更新到 ttk Python33 中 Combobox 下的列表框

python - Tkinter 按钮不会在点击时获得焦点

python - 使用 PIL 的 ImageDraw 模块

python - 在 ubuntu 树莓派中自动刷新图像

python - numpy.where 的嵌套使用

maven - mvnrepository.com 上的图标和标签

Python win32com EXCEL 返回无