突出显示单词,然后使用 tkinter 取消突出显示 [英] Highlighting words and then unhighlighting using tkinter

查看:37
本文介绍了突出显示单词,然后使用 tkinter 取消突出显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个程序可以突出显示文本框中的单词,但是,我希望能够实现的是,再次单击同一个单词时,该单词将不突出显示.这可能吗?以下是单击单词时执行操作的代码部分.希望能帮到你.

I have a program that will highlight a word in a textbox, however, what I would like to be able to achieve is when the same word is clicked again the word will then be unhighlighted. Is this possible? Below is the section of code that does stuff when a word is clicked. I hope you are able to help.

def __init__(self, parent):
        tk.Frame.__init__(self, parent)
        self.text = tk.Text(self, wrap="none")
        self.text.pack(fill="both", expand=True)

        self.text.bind("<ButtonRelease-1>", self._on_click)
        self.text.tag_configure("highlight", background="green", foreground="black")

        with open(__file__, "rU") as f:
            data = f.read()
            self.text.insert("1.0", data)

def _on_click(self, event):
            self.text.tag_add("highlight", "insert wordstart", "insert wordend")

我已经尝试过使用:

def _on_click(self, event):
    self.text.tag_remove("highlight", "1.0", "end")
    self.text.tag_add("highlight", "insert wordstart", "insert wordend")
    if self.text.tag_names == ('sel', 'highlight'):
        self.text.tag_add("highlight", "insert wordstart", "insert wordend")
    else:
        self.text.tag_remove("highlight", "1.0", "end")

但那没有运气.

推荐答案

您可以使用 tag_names 来获取某个索引处的标签列表.然后只需调用 tag_addtag_remove 取决于当前单词上是否存在标签.

You can use tag_names to get a list of tags at a certain index. Then it's just a matter of calling tag_add or tag_remove depending on whether the tag is present on the current word or not.

示例:

import tkinter as tk

class Example(object):
    def __init__(self):
        self.root = tk.Tk()
        self.text = tk.Text(self.root)
        self.text.pack(side="top", fill="both", expand=True)
        self.text.bind("<ButtonRelease-1>", self._on_click)
        self.text.tag_configure("highlight", background="bisque")

        with open(__file__, "r") as f:
            self.text.insert("1.0", f.read())

    def start(self):
        self.root.mainloop()

    def _on_click(self, event):
        tags = self.text.tag_names("insert wordstart")
        if "highlight" in tags:
            self.text.tag_remove("highlight", "insert wordstart", "insert wordend")
        else:
            self.text.tag_add("highlight", "insert wordstart", "insert wordend")

if __name__ == "__main__":    
    Example().start()

这篇关于突出显示单词,然后使用 tkinter 取消突出显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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