pythonttkinter文本widg中的getclicked标记

2024-04-26 18:14:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我在一个文本小部件中有一些标记,并为它们绑定了一个click函数。在

我的例句是“我可爱的小猫”“可爱”和“小”是带标记形容词的标记词。在

在这个click函数中,我无法找到获取我单击的字符串的方法。当我点击可爱,我想打印可爱到控制台。在

这是我到目前为止,我没有包括我如何应用标签,因为这是工作。click函数调用正确。在

    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

有办法吗?在

最好的, 迈克尔


Tags: the函数标记文本selfeventherebind
1条回答
网友
1楼 · 发布于 2024-04-26 18:14:22

我设法从光标位置提取点击标签的文本。我把它转换成一个索引,并检查了覆盖索引的标记。在

我的解决方案是:

    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))

相关问题 更多 >