[英]Python TKinter get clicked tag in text widget
i have some tags in a text widget and bound a click function to all of them. 我在文本小部件中有一些标签,并将单击功能绑定到所有标签。
My example sentence is "my cute, little cat". 我的例句是“我的猫咪可爱”。 "Cute" and "little" are the tagged words with the tag adj.
“ Cute”和“ little”是带有标签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.
当我单击cute时,我想在控制台上打印出cute。
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? 有没有办法做到这一点?
Best, Michael 最好,迈克尔
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.
我将其转换为索引,并检查了覆盖该索引的标签。
Here is my solution: 这是我的解决方案:
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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.