2015-07-12 73 views
0

我把圖案從強調: 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

您需要將regexp標誌設置爲True,然後使用適當的正則表達式。請注意,正則表達式必須遵循Tcl regular expressions的規則。

對於你的情況,你只想匹配的模式作爲一個整體的話,那麼你可以使用\m匹配一個單詞的開頭和\M到單詞的末尾匹配:

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

非常感謝你許多!工作的1000%〜 –