x01.editor: 语法高亮编辑器

学习《Tkinter GUI Programming By Example》时,发现了语法高亮编辑器和聊天程序还不错。语法高亮编辑器如下,聊天程序可在下载中获取。

1. 效果图

2. 代码

import os, sys
CurrDir = os.path.dirname(__file__)
sys.path.append(CurrDir)

import tkinter as tk 
import tkinter.ttk as ttk 
import tkinter.messagebox as msgbox 
import itertools 

from tkinter import filedialog

from editor.core import TextArea, LineNumbers, FindWindow, Highlighter, R 

class MainWindow(tk.Tk):
    def __init__(self):
        super().__init__()
        self.title("x01.editor")

        self.text_area = TextArea(self, bg="white", fg="black", undo=True)

        self.scrollbar = ttk.Scrollbar(orient="vertical", command=self.scroll_text)
        self.text_area.configure(yscrollcommand=self.scrollbar.set)

        self.line_numbers = LineNumbers(self, self.text_area,width=1, bg="grey", fg="white")
        self.highlighter = Highlighter(self.text_area, os.path.join(CurrDir,'languages/python.yaml'))

        self.scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        self.line_numbers.pack(side=tk.LEFT, fill=tk.Y)
        self.text_area.pack(side=tk.LEFT, fill=tk.BOTH, expand=1)

        self.bind_events()

        self.background = 'lightgrey'
        self.foreground = 'black'
        self.menu = tk.Menu(self, bg=self.background, fg=self.foreground)
        self.generate_menus(['file', 'help']) #'edit','tools','help'])
        self.configure(menu=self.menu)

        self.open_file = ''

        self.yaml_config()
        R.win_center(self)

    def yaml_config(self):
        config = R.load_config(os.path.join(CurrDir, 'config.yaml'))
        self.text_area.configure(font=(config['font_family'], config['font_size']))
        self.line_numbers.configure(font=(config['font_family'], config['font_size']))

    def bind_events(self):
        self.text_area.bind("<MouseWheel>", self.scroll_text)
        self.text_area.bind("<Button-4>", self.scroll_text)
        self.text_area.bind("<Button-5>", self.scroll_text)

        self.line_numbers.bind("<MouseWheel>", lambda e: "break")
        self.line_numbers.bind("<Button-4>", lambda e: "break")
        self.line_numbers.bind("<Button-5>", lambda e: "break")

        self.bind('<Control-f>', self.show_find_window)
        self.bind("<Control-n>", self.file_new)
        self.bind('<Control-o>', self.file_open)
        self.bind('<Control-s>', self.file_save)
        self.bind('<Alt-s>', self.file_saveas)
        self.bind('<Control-h>', self.help_about)

    def scroll_text(self, *args):
        if len(args) > 1:
            self.text_area.yview_moveto(args[1])
            self.line_numbers.yview_moveto(args[1])
        else:
            event = args[0]
            if event.delta:
                move = -1 * (event.delta / 120)
            else:
                if event.num == 5:
                    move = 1
                else:
                    move = -1

            self.text_area.yview_scroll(int(move), "units")
            self.line_numbers.yview_scroll(int(move) * 3, "units")

    def show_find_window(self, event=None):
        FindWindow(self.text_area)

    def generate_menus(self, items):
        win_methods = [method_name for method_name in dir(self) if callable(getattr(self, method_name))]
        tk_methods = [method_name for method_name in dir(tk.Tk) if callable(getattr(tk.Tk, method_name))]
        methods = [m for m in set(win_methods) - set(tk_methods)]
        methods = sorted(methods)
        for item in items:
            sub_menu = tk.Menu(self.menu, tearoff=0, bg=self.background, fg=self.foreground)
            match_methods = []
            for m in methods:
                if m.startswith(item):
                    match_methods.append(m)
            for m in match_methods:
                actual_method = getattr(self, m)
                shortcut = actual_method.__doc__.strip()
                name = ' '.join(m.split('_')[1:])
                sub_menu.add_command(label=name.title(), command=actual_method, accelerator=shortcut)
            self.menu.add_cascade(label=item.title(), menu=sub_menu)

    def file_new(self, event=None):
        '''
        Ctrl+N
        '''
        self.text_area.delete(1.0, tk.END)
        self.open_file = None 
        self.line_numbers.force_update()

    def file_open(self, event=None):
        '''
        Ctrl+O
        '''
        types = (('python files', '*.py'), ('All files', '*.*'))
        filename = filedialog.askopenfilename(title='x01.editor', filetypes=types)
        if filename:
            self.open_file = filename
            self.text_area.display_file_contents(filename)
            self.highlighter.highlight()
            self.line_numbers.force_update()

    def file_save(self, event=None):
        '''
        Ctrl+S
        '''
        f = self.open_file if self.open_file else None
        if f is None:
            types = (('python files', '*.py'), ('All files', '*.*'))
            f = filedialog.asksaveasfilename(title='x01.editor', filetypes=types)
        if f:
            contents = self.text_area.get(1.0, tk.END)
            with open(f, 'w') as file:
                file.write(contents)

    def file_saveas(self, event=None):
        '''
        Alt+S
        '''
        types = (('python files', '*.py'), ('All files', '*.*'))
        f = filedialog.asksaveasfilename(title='x01.editor', filetypes=types)
        if f:
            contents = self.text_area.get(1.0,tk.END)
            with open(f, 'w') as file:
                file.write(contents)

    def help_about(self, event=None):
        '''
        Ctrl+H
        '''
        msgbox.showinfo("About", "x01.editor 语法高亮编辑器")
        pass

if __name__ == '__main__':
    mw = MainWindow()
    mw.mainloop()
main
import tkinter as tk 
import tkinter.ttk as ttk 
import yaml 
import os, sys 

class TextArea(tk.Text):
    def __init__(self, master, **kwargs):
        super().__init__(**kwargs)

        self.master = master

        self.config(wrap=tk.WORD)  # CHAR NONE

        self.tag_configure('find_match', background="yellow")
        self.find_match_index = None
        self.find_search_starting_index = 1.0

        self.bind_events()

    def display_file_contents(self, path):
        with open(path, 'r') as f:
            self.delete(1.0, tk.END)
            self.insert(1.0, f.read())
            
    def bind_events(self):
        self.bind('<Control-a>', self.select_all)
        self.bind('<Control-c>', self.copy)
        self.bind('<Control-v>', self.paste)
        self.bind('<Control-x>', self.cut)
        self.bind('<Control-y>', self.redo)
        self.bind('<Control-z>', self.undo)

    def cut(self, event=None):
        self.event_generate("<<Cut>>")

    def copy(self, event=None):
        self.event_generate("<<Copy>>")

    def paste(self, event=None):
        self.event_generate("<<Paste>>")

    def undo(self, event=None):
        self.event_generate("<<Undo>>")

        return "break"

    def redo(self, event=None):
        self.event_generate("<<Redo>>")

        return "break"

    def select_all(self, event=None):
        self.tag_add("sel", 1.0, tk.END)

        return "break"

    def find(self, text_to_find):
        length = tk.IntVar()
        idx = self.search(text_to_find, self.find_search_starting_index, stopindex=tk.END, count=length)

        if idx:
            self.tag_remove('find_match', 1.0, tk.END)

            end = f'{idx}+{length.get()}c'
            self.tag_add('find_match', idx, end)
            self.see(idx)

            self.find_search_starting_index = end
            self.find_match_index = idx
        else:
            if self.find_match_index != 1.0:
                if msg.askyesno("No more results", "No further matches. Repeat from the beginning?"):
                    self.find_search_starting_index = 1.0
                    self.find_match_index = None
                    return self.find(text_to_find)
            else:
                msg.showinfo("No Matches", "No matching text found")

    def replace_text(self, target, replacement):
        if self.find_match_index:

            end = f"{self.find_match_index}+{len(target)}c"
            self.replace(self.find_match_index, end, replacement)

            self.find_search_starting_index = f"{self.find_match_index} linestart"
            self.find_match_index = None

    def cancel_find(self):
        self.find_search_starting_index = 1.0
        self.find_match_index = None
        self.tag_remove('find_match', 1.0, tk.END)

class LineNumbers(tk.Text):
    def __init__(self, master, text_widget, **kwargs):
        super().__init__(master, **kwargs)

        self.text_widget = text_widget
        self.text_widget.bind('<KeyPress>', self.on_key_press)

        self.insert(1.0, '1')
        self.configure(state='disabled')

    def on_key_press(self, event=None):
        final_index = str(self.text_widget.index(tk.END))
        num_of_lines = final_index.split('.')[0]
        line_numbers_string = "\n".join(str(no + 1) for no in range(int(num_of_lines)))
        width = len(str(num_of_lines))

        self.configure(state='normal', width=width)
        self.delete(1.0, tk.END)
        self.insert(1.0, line_numbers_string)
        self.configure(state='disabled')

    def force_update(self):
        self.on_key_press()

class R:
    CurrentDir = os.path.dirname(__file__)

    @classmethod
    def load_config(cls, path):
        with open(path, 'r') as f:
            try:
                config = yaml.load(f)
            except yaml.YAMLError as e:
                print(e)
                return
        return config 

    @classmethod
    def win_center(cls, win, w=800,h=600):
        x = (win.winfo_screenwidth() - w) // 2
        y = (win.winfo_screenheight() - h) // 2
        win.geometry('{}x{}+{}+{}'.format(w,h,x,y))

class FindWindow(tk.Toplevel):
    def __init__(self, master, **kwargs):
        super().__init__(**kwargs)

        self.master = master

        self.geometry('350x100')
        self.title('Find and Replace')
        self.transient(self.master)

        self.text_to_find = tk.StringVar()
        self.text_to_replace_with = tk.StringVar()

        top_frame = tk.Frame(self)
        middle_frame = tk.Frame(self)
        bottom_frame = tk.Frame(self)

        find_entry_label = tk.Label(top_frame, text="Find: ")
        self.find_entry = ttk.Entry(top_frame, textvar=self.text_to_find)

        replace_entry_label = tk.Label(middle_frame, text="Replace: ")
        self.replace_entry = ttk.Entry(middle_frame, textvar=self.text_to_replace_with)

        self.find_button = ttk.Button(bottom_frame, text="Find", command=self.on_find)
        self.replace_button = ttk.Button(bottom_frame, text="Replace", command=self.on_replace)
        self.cancel_button = ttk.Button(bottom_frame, text="Cancel", command=self.on_cancel)

        find_entry_label.pack(side=tk.LEFT, padx=(20, 0))
        self.find_entry.pack(side=tk.LEFT, fill=tk.X, expand=1)

        replace_entry_label.pack(side=tk.LEFT)
        self.replace_entry.pack(side=tk.LEFT, fill=tk.X, expand=1)

        self.find_button.pack(side=tk.LEFT, padx=(85, 0))
        self.replace_button.pack(side=tk.LEFT, padx=(20, 20))
        self.cancel_button.pack(side=tk.RIGHT, padx=(0, 30))

        top_frame.pack(side=tk.TOP, expand=1, fill=tk.X, padx=30)
        middle_frame.pack(side=tk.TOP, expand=1, fill=tk.X, padx=30)
        bottom_frame.pack(side=tk.TOP, expand=1, fill=tk.X)

        self.find_entry.focus_force()

        self.protocol("WM_DELETE_WINDOW", self.on_cancel)

    def on_find(self):
        self.master.find(self.text_to_find.get())

    def on_replace(self):
        self.master.replace_text(self.text_to_find.get(), self.text_to_replace_with.get())

    def on_cancel(self):
        self.master.cancel_find()
        self.destroy()

class Highlighter:
    def __init__(self, text_widget, syntax_file):
        self.text_widget = text_widget
        self.syntax_file = syntax_file
        self.categories = None
        self.numbers_color = "blue"

        self.disallowed_previous_chars = ["_", "-", "."]

        self.parse_syntax_file()

        self.text_widget.bind('<KeyRelease>', self.on_key_release)

    def on_key_release(self, event=None):
        self.highlight()

    def parse_syntax_file(self):
        with open(self.syntax_file, 'r') as stream:
            try:
                config = yaml.load(stream)
            except yaml.YAMLError as error:
                print(error)
                return

        self.categories = config['categories']
        self.numbers_color = config['numbers']['color']
        self.strings_color = config['strings']['color']

        self.configure_tags()

    def configure_tags(self):
        for category in self.categories.keys():
            color = self.categories[category]['color']
            self.text_widget.tag_configure(category, foreground=color)

        self.text_widget.tag_configure("number", foreground=self.numbers_color)
        self.text_widget.tag_configure("string", foreground=self.strings_color)

    def highlight(self, event=None):
        length = tk.IntVar()
        for category in self.categories:
            matches = self.categories[category]['matches']
            for keyword in matches:
                start = 1.0
                keyword = keyword + "[^A-Za-z_-]"
                idx = self.text_widget.search(keyword, start, stopindex=tk.END, count=length, regexp=1)
                while idx:
                    char_match_found = int(str(idx).split('.')[1])
                    line_match_found = int(str(idx).split('.')[0])
                    if char_match_found > 0:
                        previous_char_index = str(line_match_found) + '.' + str(char_match_found - 1)
                        previous_char = self.text_widget.get(previous_char_index, previous_char_index + "+1c")

                        if previous_char.isalnum() or previous_char in self.disallowed_previous_chars:
                            end = f"{idx}+{length.get() - 1}c"
                            start = end
                            idx = self.text_widget.search(keyword, start, stopindex=tk.END, regexp=1)
                        else:
                            end = f"{idx}+{length.get() - 1}c"
                            self.text_widget.tag_add(category, idx, end)

                            start = end
                            idx = self.text_widget.search(keyword, start, stopindex=tk.END, regexp=1)
                    else:
                        end = f"{idx}+{length.get() - 1}c"
                        self.text_widget.tag_add(category, idx, end)

                        start = end
                        idx = self.text_widget.search(keyword, start, stopindex=tk.END, regexp=1)

        self.highlight_regex(r"(\d)+[.]?(\d)*", "number")
        self.highlight_regex(r"[\'][^\']*[\']", "string")
        self.highlight_regex(r"[\"][^\"]*[\"]", "string")

    def highlight_regex(self, regex, tag):
        length = tk.IntVar()
        start = 1.0
        idx = self.text_widget.search(regex, start, stopindex=tk.END, regexp=1, count=length)
        while idx:
            end = f"{idx}+{length.get()}c"
            self.text_widget.tag_add(tag, idx, end)

            start = end
            idx = self.text_widget.search(regex, start, stopindex=tk.END, regexp=1, count=length)
    
if __name__ == "__main__":
    w = tk.Tk()
    h = Highlighter(tk.Text(w), os.path.join(CurrDir,'languages/python.yaml'))
    w.mainloop()
core.py

3. 下载

x01.lab

posted on 2020-05-12 10:42  x01  阅读(498)  评论(0编辑  收藏  举报

导航