Python Tkinter文本语法突出显示不起作用

时间:2015-08-11 18:35:07

标签: python tkinter

我正在使用Brian Oakley's CustomText类,其中包含syntax highlighting。不幸的是,当我配置标签并创建突出显示模式时,highlighting似乎不起作用。以下是我的代码:

import tkinter as tk


class CustomText(tk.Text):
    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.
        '''

        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
            self.mark_set("matchStart", index)
            self.mark_set("matchEnd", "%s+%sc" % (index, count.get()))
            self.tag_add(tag, "matchStart", "matchEnd")

class Arshi(tk.Frame):
    def __init__(self, *args, **kwargs):
        tk.Frame.__init__(self, *args, **kwargs)
        self.createtext()

    def createtext(self):
        self.text = CustomText(self, bd=0, font=("Courier", 9))
        self.text.tag_configure("declaration", foreground="#376899")
        self.text.highlight_pattern("asdf", "declaration")
        self.text.pack()

if __name__ == "__main__":
    root = tk.Tk()
    root.title("Arshi")
    window = Arshi(root).pack(side="top", fill="both", expand=True)
    root.mainloop()

1 个答案:

答案 0 :(得分:0)

插入文本后,您必须调用highlight_pattern函数。它不会自动发生。