【问题标题】:Advanced Pattern Highlighting高级模式突出显示
【发布时间】:2015-07-12 07:05:56
【问题描述】:

我从以下位置获得了突出显示的模式: How to highlight text in a tkinter Text widget

但我一直在努力改进它,虽然我失败了。问题是,如果模式是“读取”,它仍然会从“readily”或其他带有“read”的东西中突出显示“read”。这是示例代码:

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

我想得到一些帮助,让它只有在“阅读”这个词并且它周围没有任何东西时才着色。

【问题讨论】:

    标签: python text tkinter widget


    【解决方案1】:

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

    对于您的情况,您只想匹配整个单词的模式,因此您可以使用 \m 匹配单词的开头,使用 \M 匹配单词的结尾:

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

    【讨论】:

      猜你喜欢
      • 2016-05-30
      • 1970-01-01
      • 2020-09-29
      • 2022-12-03
      • 2010-09-24
      • 1970-01-01
      • 2012-04-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多