Python TKinter 在文本小部件中获得点击标签 [英] Python TKinter get clicked tag in text widget

查看:47
本文介绍了Python TKinter 在文本小部件中获得点击标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在文本小部件中有一些标签,并将点击功能绑定到所有标签.

i have some tags in a text widget and bound a click function to all of them.

我的例句是我可爱的小猫".可爱"和小"是带有adj的标记词.

My example sentence is "my cute, little cat". "Cute" and "little" are the tagged words with the tag adj.

在这个点击功能中,我不知道如何获取我点击的字符串.当我点击可爱时,我想将可爱打印到控制台.

In this click function i can not figure out the way to get the string i clicked. When i click on cute i want to print cute to the console.

这是我到目前为止所拥有的,我没有包括我如何应用标签,因为这有效.正确调用了点击函数.

This is what i have so far, i did not include how i apply the tag, since this works. The click function is called correctly.

    def __init__(self, master):
        # skipped some stuff here
        self.MT.tag_config('adj', foreground='orange')
        # here i bind the click function
        self.MT.tag_bind('adj', '<Button-1>', self.click)

    def click(self, event):
        print(dir(event))
        # i want to print the clicked tag text here

有没有办法做到这一点?

Is there a way to do this?

最好的,迈克尔

推荐答案

我设法从光标位置提取了点击标签的文本.我将其转换为索引并检查覆盖索引的标签.

I managed to extract the text of the clicked label from the cursor position. I converted it to an index and checked for the tag that covered the index.

这是我的解决方案:

    def click(self, event):
        # get the index of the mouse click
        index = self.MT.index("@%s,%s" % (event.x, event.y))

        # get the indices of all "adj" tags
        tag_indices = list(self.MT.tag_ranges('adj'))

        # iterate them pairwise (start and end index)
        for start, end in zip(tag_indices[0::2], tag_indices[1::2]):
            # check if the tag matches the mouse click index
            if self.MT.compare(start, '<=', index) and self.MT.compare(index, '<', end):
                # return string between tag start and end
                return (start, end, self.MT.get(start, end))

这篇关于Python TKinter 在文本小部件中获得点击标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆