2010-09-23 116 views
11

我想知道如何根據某些模式更改某些單詞和表達式的樣式。如何突出顯示tkinter文本部件中的文本

我正在使用Tkinter.Text小部件,我不確定如何做這樣的事情(在文本編輯器中的語法高亮相同的想法)。我不確定即使這是用於此目的的正確小部件。

+0

這是正確的部件。看看['idle']是什麼(http://hg.python.org/cpython/file/63a00d019bb2/Lib/idlelib)。 – tzot 2011-11-12 18:46:29

+0

@tzot你至少可以更好地指出應該看到的文件。 'idlelib'包含許多文件和模塊等,在我看來,找到一些東西時有點困難,沒有真實的文檔,而且大多數人沒有太多經驗。我將首先引導本網站的用戶閱讀以下文章:https://docs.python.org/3.5/library/idle.html – nbro 2015-07-12 16:18:34

回答

31

這是適用於這些目的的正確小部件。基本概念是,將屬性分配給標籤,並將標籤應用於小部件中的文本範圍。您可以使用文本小部件的search命令來查找與您的模式相匹配的字符串,這會返回足夠的信息,將匹配的標籤應用於匹配的範圍。

有關如何將標籤應用於文本的示例,請參閱我對問題Advanced Tkinter text box?的回答。這不完全是你想要做的,但它顯示了基本的概念。

以下是如何擴展Text類以包含突出顯示與模式匹配的文本的方法的示例。

在此代碼中,模式必須是字符串,它不能是編譯的正則表達式。此外,該模式必須符合Tcl's syntax rules for regular expressions

class CustomText(tk.Text): 
    '''A text widget with a new method, highlight_pattern() 

    example: 

    text = CustomText() 
    text.tag_configure("red", foreground="#ff0000") 
    text.highlight_pattern("this should be red", "red") 

    The highlight_pattern method is a simplified python 
    version of the tcl code at http://wiki.tcl.tk/3246 
    ''' 
    def __init__(self, *args, **kwargs): 
     tk.Text.__init__(self, *args, **kwargs) 

    def highlight_pattern(self, pattern, tag, start="1.0", end="end", 
          regexp=False): 
     '''Apply the given tag to all text that matches the given pattern 

     If 'regexp' is set to True, pattern will be treated as a regular 
     expression according to Tcl's regular expression syntax. 
     ''' 

     start = self.index(start) 
     end = self.index(end) 
     self.mark_set("matchStart", start) 
     self.mark_set("matchEnd", start) 
     self.mark_set("searchLimit", end) 

     count = tk.IntVar() 
     while True: 
      index = self.search(pattern, "matchEnd","searchLimit", 
           count=count, regexp=regexp) 
      if index == "": break 
      if count.get() == 0: break # degenerate pattern which matches zero-length strings 
      self.mark_set("matchStart", index) 
      self.mark_set("matchEnd", "%s+%sc" % (index, count.get())) 
      self.tag_add(tag, "matchStart", "matchEnd") 
+0

謝謝,這對我非常有幫助!你能告訴我如何改變它,所以它接受正則表達式作爲模式,但? (當我嘗試時,我得到'TypeError:'_sre.SRE_Pattern'對象沒有屬性'__getitem __'') – Lastalda 2012-10-08 12:02:16

+0

@Lastalda:文本小部件'search'方法接受一個名爲'regexp'的關鍵字參數。如果將此設置爲「True」,則該模式將被視爲正則表達式。我已更新我的答案以包含此功能。不幸的是,'search'方法中tkinter特有的文檔有點稀疏。如果你閱讀官方的tk文檔,它的解釋會更好一些,但是你必須從tcl到python做一個小小的心理翻譯。請參閱http://tcl.tk/man/tcl8.5/TkCmd/text.htm#M120 – 2012-10-08 14:03:39

+0

感謝您的關注。但我仍然得到同樣的錯誤。 :(我是否做了錯誤的正則表達式?我使用'w.HighlightPattern(re.compile(「R \ d +」),「藍色」)'我得到錯誤追溯'文件「C:\ Python27 \ lib \如果模式和模式[0] ==' - ':args.append(' - ')TypeError:'_sre.SRE_Pattern'對象沒有屬性'__getitem __'' – Lastalda 2012-10-09 07:26:11