# 文本编辑器
from tkinter import *
import tkinter.messagebox
from tkinter.filedialog import askopenfilename
from tkinter.filedialog import asksaveasfilename
class FileEditor:
def __init__(self):
window = Tk()
window.title("Simple Text Editor")
menubar = Menu(window)
window.config(menu=menubar)
operationMenu = Menu(menubar, tearoff=0)
menubar.add_cascade(label="File", menu=operationMenu)
operationMenu.add_command(label="Open", command=self.openFile)
operationMenu.add_command(label="Save", command=self.saveFile)
frame0 = Frame(window)
frame0.grid(row=1, column=1, sticky=W)
Button(frame0, text="Open", command=self.openFile).grid(row=1, column=1, sticky=W)
Button(frame0, text="Save", command=self.saveFile).grid(row=1, column=2)
frame1 = Frame(window)
frame1.grid(row=2, column=1)
scrollbar = Scrollbar(frame1)
scrollbar.pack(side=RIGHT, fill=Y)
self.text = Text(frame1, width=80, height=40, wrap=WORD, yscrollcommand=scrollbar.set)
self.text.pack()
scrollbar.config(command=self.text.yview)
window.mainloop()
def openFile(self):
self.text.delete("1.0", "end")
try:
filenameforReading = askopenfilename()
infile = open(filenameforReading, "r", encoding="utf-8")
self.text.insert(END, infile.read())
except UnicodeDecodeError:
tkinter.messagebox.showerror("error", "打开文件失败!")
finally:
infile.close()
def saveFile(self):
try:
filenameforWriting = asksaveasfilename()
outfile = open(filenameforWriting, "w", encoding="utf-8")
outfile.write(self.text.get(1.0, END))
except PermissionError:
tkinter.messagebox.showerror("error", "保存文件失败!")
finally:
outfile.close()
FileEditor()
暂无评论