2014-04-16 218 views
1

我想知道是否可以在Tkinter的Text小部件中爲特定關鍵字着色。我基本上試圖編寫一個編程文本編輯器,所以if聲明可能是一種顏色,而else聲明會是另一種顏色。謝謝閱讀。Tkinter Text Widget關鍵字着色

+0

可能重複[如何改變在調色文本組件某些字的顏色?( http://stackoverflow.com/questions/14786507/how-to-change-the-color-of-certain-words-in-the-tkinter-text-widget) – thecoder16

+0

點擊鏈接獲取答案 – thecoder16

+0

我試過這個但不幸的是我認爲這個教程展示瞭如何給預先插入的單詞添加顏色,而不是用戶類型的單詞es in。 – user3286192

回答

0

執行此操作的一種方法是將函數綁定到Key事件,該事件搜索匹配的字符串並將標記應用於修改該字符串屬性的任何匹配字符串。下面是一個例子,有評論說:改編自here

更多關於Text部件

from Tkinter import * 

# dictionary to hold words and colors 
highlightWords = {'if': 'green', 
        'else': 'red' 
        } 

def highlighter(event): 
    '''the highlight function, called when a Key-press event occurs''' 
    for k,v in highlightWords.iteritems(): # iterate over dict 
     startIndex = '1.0' 
     while True: 
      startIndex = text.search(k, startIndex, END) # search for occurence of k 
      if startIndex: 
       endIndex = text.index('%s+%dc' % (startIndex, (len(k)))) # find end of k 
       text.tag_add(k, startIndex, endIndex) # add tag to k 
       text.tag_config(k, foreground=v)  # and color it with v 
       startIndex = endIndex # reset startIndex to continue searching 
      else: 
       break 

root = Tk() 
text = Text(root) 
text.pack() 

text.bind('<Key>', highlighter) # bind key event to highlighter() 

root.mainloop() 

here

+0

謝謝,現在它使 – user3286192

+0

任何機會是否有可能將所有整數添加到突出顯示的單詞?或者所有帶括號的詞? – user3286192

+0

你的意思是在字典中加0-9嗎?如果是這樣,是的,這是可能的。只要是可接受的格式,您可以添加任何您想要的密鑰。 – atlasologist