想要制作簡單的python腳本編輯器,其中文字輸入代碼部分使用Tkinter中的Text控件即可實作。
但是問題是,如何實作高亮呢?參考python自帶的編輯器:python27/vidle檔案夾中的代碼。
實作效果為:

其中主要思路就是在Text中每輸入一行代碼,都通過正則比對,查找是不是需要高亮效果,道理很簡單,但是問題就是在使用Text控件的時候,通過光标輸入的時候,似乎不能找到光标對應的位置,是以,人家的編輯器代碼中,提供了WidgetRedirector.py檔案,其作用主要是解決控件的輸入操作執行Tk庫裡面的insert,而跳過了Tkinter庫對應Text類中的insert函數。
該類的作用就是使用register函數注冊insert的函數funtion,當往Text輸入時,調用了funtion,然後從這個funtion中,即可得到文字輸入的位置,而原始的insert函數中,往Text書寫的操作,是通過該檔案中的OriginalCommand類實作的。
其中的
WidgetRedirector類和OriginalCommand類直接拷貝即可。
而顔色高亮主要在ColorDelegator.py檔案中實作,可以使用其中的正規表達式。
實作Text高亮的部分為:
class Test(object):
def __init__(self,parent):
self.parent = parent
self.text = Text(self.parent)
self.text.pack()
self.text.focus_set()
self.redir = WidgetRedirector(self.text)
self.redir.insert = self.redir.register("insert", self.m_insert)
self.redir.delete = self.redir.register("delete", self.m_delete)
self.prog = prog
self.tagdefs = {‘COMMENT‘: {‘foreground‘: ‘#dd0000‘, ‘background‘: ‘#ffffff‘}, ‘DEFINITION‘: {‘foreground‘: ‘#0000ff‘, ‘background‘: ‘#ffffff‘}, ‘BUILTIN‘: {‘foreground‘: ‘#900090‘, ‘background‘: ‘#ffffff‘}, ‘hit‘: {‘foreground‘: ‘#ffffff‘, ‘background‘: ‘#000000‘}, ‘STRING‘: {‘foreground‘: ‘#00aa00‘, ‘background‘: ‘#ffffff‘}, ‘KEYWORD‘: {‘foreground‘: ‘#ff7700‘, ‘background‘: ‘#ffffff‘}, ‘ERROR‘: {‘foreground‘: ‘#000000‘, ‘background‘: ‘#ff7777‘}, ‘TODO‘: {‘foreground‘: None, ‘background‘: None}, ‘SYNC‘: {‘foreground‘: None, ‘background‘: None}, ‘BREAK‘: {‘foreground‘: ‘black‘, ‘background‘: ‘#ffff55‘}}
for tag, cnf in self.tagdefs.items():
if cnf:
self.text.tag_configure(tag, **cnf)
def m_delete(self, index1, index2=None):
index1 = self.text.index(index1)
self.redir.delete(index1, index2)
self.notify_range(index1,index1)
def m_insert(self, index, chars, *args):
index = self.text.index(index)
self.redir.insert(index, chars, *args)
self.notify_range(index, index + "+%dc" % len(chars))
def notify_range(self, index1, index2=None):
first = index1[0]+‘.0‘
line = self.text.get(first, index2)
for tag in self.tagdefs.keys():
self.text.tag_remove(tag, first, index2)
chars = line
m = self.prog.search(chars)
while m:
for key, value in m.groupdict().items():
if value:
a, b = m.span(key)
self.text.tag_add(key,
first + "+%dc" % a,
first + "+%dc" % b)
m = self.prog.search(chars, m.end())
由此即可完成簡單的編輯器。