Python TKinter 获取文本小部件中的点击标签

标签 python tkinter

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

我的例句是“我可爱的小猫”。 “可爱”和“小”是带有标签 adj 的标签词。

在这个点击函数中,我无法弄清楚如何获取我点击的字符串。当我单击“可爱”时,我想将“可爱”打印到控制台。

这是我到目前为止所拥有的,我没有包括如何应用标签,因为这有效。正确调用了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

有办法做到这一点吗?

最好, 迈克尔

最佳答案

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

这是我的解决方案:

    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 获取文本小部件中的点击标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33954343/

相关文章:

Python Tkinter 应用程序在 Mac OS X 上导致 fork()/exec() 错误

python - 什么是正确的 : widget. rowconfigure 或 widget.grid_rowconfigure?

Python/tkinter - 如何在 Windows 上获取包括边框的窗口大小?

python - BeautifulSoup 用原始 xml 替换标签而不解析/转义

python - 继承 numpy.vectorize-ed 函数

python - 根据开始索引和结束索引删除字符串

python - 当我使用 idlelib 突出显示语法时如何避免更改 tkinter 中选定文本的颜色

python - Python 中的 TypeError - Beautiful Soup

python - Pickling cv2.KeyPoint 导致 PicklingError

python - ttk.combobox 选择列表