我想知道是否可以在Tkinter的Text小部件中爲特定關鍵字着色。我基本上試圖編寫一個編程文本編輯器,所以if
聲明可能是一種顏色,而else
聲明會是另一種顏色。謝謝閱讀。Tkinter Text Widget關鍵字着色
回答
執行此操作的一種方法是將函數綁定到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
的謝謝,現在它使 – user3286192
任何機會是否有可能將所有整數添加到突出顯示的單詞?或者所有帶括號的詞? – user3286192
你的意思是在字典中加0-9嗎?如果是這樣,是的,這是可能的。只要是可接受的格式,您可以添加任何您想要的密鑰。 – atlasologist
- 1. Tkinter Text Widget顏色特定文本
- 2. Vim:關鍵字着色
- 3. Python Tkinter Text Widget .get方法錯誤
- 4. Python Tkinter Text Widget with Auto&Custom Scroll
- 5. Tkinter Text Widget中的字符串中包含的標籤
- 6. 的Widget風格的主題顏色關鍵字
- 7. 着色關閉點
- 8. Tkinter Spinbox Widget
- 9. Tkinter - 關鍵字爭論重複
- 10. 如何從Tkinter Text Box Widget獲取輸入?
- 11. 旨在刪除Tkinter Text Widget內容的線程無法運行。
- 12. Tkinter Text/ScrolledText新行
- 13. 從TEXT WIDGET改變背景顏色不可能嗎?
- 14. 意外的關鍵字參數,'text'
- 15. 關鍵字在Visual Studio 2015中未着色
- 16. Flex Builder 3:語法着色,添加關鍵字
- 17. 在eclipse中擴展關鍵字列表以供着色
- 18. 如何使用HTML爲關鍵字着色?
- 19. 通過關鍵字過濾日誌文件並着色輸出
- 20. 在Emacs中沒有着色的C++關鍵字
- 21. Tkinter Entry Widget with Overrideredirect and Fullscreen
- 22. Sublime Text 3更改語法着色?
- 23. 如何在Tkinter畫布中爲子字符串着色
- 24. Python關鍵字角色
- 25. libGDX - 自定義着色器TEXT按鈕字體
- 26. Tkinter Text selection_get()錯誤
- 27. Python Tkinter Entry Widget覆蓋
- 28. 從tkinter Widget導入模塊
- 29. Python Tkinter Scrollable Text,滑塊不出現
- 30. Tkinter窗口關鍵事件
可能重複[如何改變在調色文本組件某些字的顏色?( http://stackoverflow.com/questions/14786507/how-to-change-the-color-of-certain-words-in-the-tkinter-text-widget) – thecoder16
點擊鏈接獲取答案 – thecoder16
我試過這個但不幸的是我認爲這個教程展示瞭如何給預先插入的單詞添加顏色,而不是用戶類型的單詞es in。 – user3286192