高级模式突出显示

时间:2015-07-12 07:05:57

标签: python text tkinter widget

我的模式突出显示: How to highlight text in a tkinter Text widget

但是我一直试图改进它,尽管我失败了。问题是如果模式是“读取”,它仍然会突出显示“读”来自“容易”或其他带有“读”的东西。这是示例代码:

from tkinter import *

class Ctxt(Text): # Custom Text Widget with Highlight Pattern   - - - - -
    # Credits to the owner of this custom class - - - - - - - - - - - - -
    def __init__(self, *args, **kwargs):
        Text.__init__(self, *args, **kwargs)

    def highlight_pattern(self, pattern, tag, start="1.0", end="end",
                          regexp=False):
        start = self.index(start)
        end = self.index(end)
        self.mark_set("matchStart", start)
        self.mark_set("matchEnd", start)
        self.mark_set("searchLimit", end)
        count = IntVar()
        while True:
            index = self.search(pattern, "matchEnd","searchLimit",
                                count=count, regexp=regexp)
            if index == "": break
            self.mark_set("matchStart", index)
            self.mark_set("matchEnd", "%s+%sc" % (index, count.get()))
            self.tag_add(tag, "matchStart", "matchEnd")
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -


# Root Window Creation  - - - -
root = Tk()
root.geometry("320x240")
root.title("Sample GUI")
# - - - - - - - - - - - - - - -


# Text Widget - - - - - - - - - - - - - - -
Wtxt = Ctxt(root)
Wtxt.pack(expand = True, fill= BOTH)
Wtxt.insert("1.0","red read rid ready readily")
# - - - - - - - - - - - - - - - - - - - - -

# Highlight pattern - - - - - - - - -
Wtxt.tag_config('green', foreground="green")
Wtxt.highlight_pattern('read','green')



# Mainloop  -
mainloop()
# - - - - - -

我希望能有一些帮助,只有当这个词被“读”并且没有任何东西时才能使它变色。

1 个答案:

答案 0 :(得分:1)

您需要将regexp标记设置为True,然后使用适当的正则表达式。请注意,正则表达式必须遵循Tcl regular expressions的规则。

对于您的情况,您希望仅将模式与整个单词匹配,因此您可以使用\m来匹配单词的开头,并使用\M来匹配单词的结尾:

Wtxt.highlight_pattern('\mread\M','green', regexp=True)