Tkinter制作簡單的python編輯器


想要制作簡單的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())

 由此即可完成簡單的編輯器。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM