簡體   English   中英

Python TKinter在文本小部件中獲得單擊的標記

[英]Python TKinter get clicked tag in text widget

我在文本小部件中有一些標簽,並將單擊功能綁定到所有標簽。

我的例句是“我的貓咪可愛”。 “ Cute”和“ little”是帶有標簽adj的標記單詞。

在此單擊功能中,我無法弄清楚獲取單擊的字符串的方式。 當我單擊cute時,我想在控制台上打印出cute。

到目前為止,這是我所擁有的,因為該方法有效,所以我未包括如何應用標簽。 單擊函數被正確調用。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM