python tkinter编写一个具有保存文件、读取文件功能的简易记事本程序
时间: 2024-03-09 18:46:19 浏览: 205
好的,以下是一个简易的记事本程序:
```python
import tkinter as tk
from tkinter import filedialog
class Notepad:
def __init__(self, master):
self.master = master
self.master.title("记事本")
# 创建文本框
self.text = tk.Text(self.master, undo=True)
self.text.pack(expand=True, fill='both')
# 创建菜单栏
self.menu_bar = tk.Menu(self.master)
self.master.config(menu=self.menu_bar)
# 文件菜单
file_menu = tk.Menu(self.menu_bar, tearoff=False)
file_menu.add_command(label="新建", accelerator="Ctrl+N", command=self.new_file)
file_menu.add_command(label="打开", accelerator="Ctrl+O", command=self.open_file)
file_menu.add_command(label="保存", accelerator="Ctrl+S", command=self.save_file)
file_menu.add_command(label="另存为", accelerator="Ctrl+Shift+S", command=self.save_file_as)
file_menu.add_separator()
file_menu.add_command(label="退出", accelerator="Alt+F4", command=self.master.quit)
self.menu_bar.add_cascade(label="文件", menu=file_menu)
# 编辑菜单
edit_menu = tk.Menu(self.menu_bar, tearoff=False)
edit_menu.add_command(label="撤销", accelerator="Ctrl+Z", command=self.text.edit_undo)
edit_menu.add_command(label="重做", accelerator="Ctrl+Y", command=self.text.edit_redo)
edit_menu.add_separator()
edit_menu.add_command(label="剪切", accelerator="Ctrl+X", command=self.cut)
edit_menu.add_command(label="复制", accelerator="Ctrl+C", command=self.copy)
edit_menu.add_command(label="粘贴", accelerator="Ctrl+V", command=self.paste)
edit_menu.add_separator()
edit_menu.add_command(label="全选", accelerator="Ctrl+A", command=self.select_all)
self.menu_bar.add_cascade(label="编辑", menu=edit_menu)
# 绑定快捷键
self.master.bind("<Control-n>", lambda event: self.new_file())
self.master.bind("<Control-o>", lambda event: self.open_file())
self.master.bind("<Control-s>", lambda event: self.save_file())
self.master.bind("<Control-S>", lambda event: self.save_file_as())
def new_file(self):
self.text.delete(1.0, 'end')
def open_file(self):
file = filedialog.askopenfile(mode='r')
if file is not None:
content = file.read()
self.text.delete(1.0, 'end')
self.text.insert('end', content)
file.close()
def save_file(self):
if not hasattr(self, 'file_path'):
self.save_file_as()
else:
content = self.text.get(1.0, 'end')
with open(self.file_path, 'w') as file:
file.write(content)
def save_file_as(self):
file = filedialog.asksaveasfile(mode='w', defaultextension=".txt")
if file is not None:
content = self.text.get(1.0, 'end')
file.write(content)
file.close()
self.file_path = file.name
def cut(self):
self.text.event_generate("<<Cut>>")
def copy(self):
self.text.event_generate("<<Copy>>")
def paste(self):
self.text.event_generate("<<Paste>>")
def select_all(self):
self.text.tag_add('sel', '1.0', 'end')
if __name__ == '__main__':
root = tk.Tk()
app = Notepad(root)
root.mainloop()
```
这个记事本程序具有保存文件、读取文件的功能。你可以使用文件菜单中的选项或者快捷键来进行操作。同时,你也可以使用编辑菜单中的选项或者快捷键来进行文本编辑。
阅读全文