Text Editor

题目要求:

Notepad style application that can open, edit, and save text documents. 

Add syntax highlighting and other features.

下面的代码实现了部分第一行题目要求

没有实现第二行题目要求(语法高亮)。没时间做,欢迎评论

import tkinter
from tkinter import *
from tkinter.ttk import Scrollbar

root = tkinter.Tk()  # 类的对象化, 创建一个GUI对象
root.title("TextEditor")  # 窗口名称
root.geometry("600x400")  # 窗口尺寸
enter_file = tkinter.Entry(root)  # 类的对象化, 在GUI中创建一个输入框
enter_file.pack()  # 输入框的放置(必备语句)
word = tkinter.Text(root, undo=True)   # 类的对象化, 在GUI中创建一个显示框
word.pack()
scroll_bar = Scrollbar(root)  # 类的对象化, 在GUI中创建一个滚动条
scroll_bar.config(command=word.yview)  # 关联显示框与滚动条
word.config(yscrollcommand=scroll_bar.set, width=20, height=20, background='#ffffff')
word.pack(side=LEFT, fill=BOTH, expand=1)
scroll_bar.pack(side=RIGHT, fill=Y)
menu = tkinter.Menu(root)  # 类的对象化,在GUI中创建一个菜单栏
root.config(menu=menu)   # 关联

def openfile():
    file_path = enter_file.get()  # 获取输入框的内容
    with open(file_path) as fp:
        content = fp.read()  # 读取文件
        word.delete(0.0, tkinter.END)  # 清空显示框
        word.insert(tkinter.END, content)  # 显示读取的文件


def savefile():
    content = word.get(0.0, tkinter.END)
    file_path = enter_file.get()
    with open(file_path, 'w') as fw:
        fw.write(content)   # 将显示文本框的一切内容保存到原文件,也就是编辑功能


def undo():
    word.edit_undo()  # 撤销上一步操作功能


button_o = tkinter.Button(root, text='open', command=openfile)  # 设置按钮标签与点击之后的动作
button_s = tkinter.Button(root, text='save', command=savefile)
button_o.pack()
button_s.pack()
menu.add_command(label='撤销', command=undo)  # 设置菜单栏标签与相应的动作

root.mainloop()  # 必备语句, 进入死循环  让窗口一直显示


# 调用:
# 在新打开的GUI界面之中输入txt文件的完整绝对路径,别忘记文件名后缀!
# 即可实现:打开,编辑,撤销,保存功能

猜你喜欢

转载自www.cnblogs.com/YlnChen/p/12588425.html