【问题标题】:Python: How do I associate Tkinter text tags with information and access them in an event?Python:如何将 Tkinter 文本标签与信息相关联并在事件中访问它们?
【发布时间】:2014-06-10 07:50:08
【问题描述】:

我在 tkinter 中使用了一个 Text 小部件,并与它关联了一些标签,如下所示:

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

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

基本上所有包含错误的文本都被标记为“err”。现在我想访问带有悬停标签的相关错误消息,但我不知道如何知道悬停的标签。

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

如果我可以提取悬停标签的范围,它将被解决。关于如何实现这一点的任何想法?

【问题讨论】:

    标签: python tags tkinter


    【解决方案1】:

    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 小部件,这可能不是问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-02-10
      • 2014-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多