pythontkinter记事本代码
时间: 2023-07-02 20:13:05 浏览: 108
python tkinter写的记事本(代码行数400+,各种tkinter均使用了)
5星 · 资源好评率100%
以下是一个简单的Python Tkinter记事本的代码示例:
```python
import tkinter as tk
from tkinter import messagebox
from tkinter.filedialog import asksaveasfilename, askopenfilename
class Notepad:
def __init__(self, root):
self.root = root
self.root.title("记事本")
self.text_area = tk.Text(self.root, undo=True)
self.text_area.pack(expand=True, fill="both")
self.menu_bar = tk.Menu(self.root)
self.file_menu = tk.Menu(self.menu_bar, tearoff=0)
self.file_menu.add_command(label="新建", accelerator="Ctrl+N", command=self.new_file)
self.file_menu.add_command(label="打开", accelerator="Ctrl+O", command=self.open_file)
self.file_menu.add_command(label="保存", accelerator="Ctrl+S", command=self.save_file)
self.file_menu.add_command(label="另存为", accelerator="Ctrl+Shift+S", command=self.save_file_as)
self.menu_bar.add_cascade(label="文件", menu=self.file_menu)
self.edit_menu = tk.Menu(self.menu_bar, tearoff=0)
self.edit_menu.add_command(label="撤销", accelerator="Ctrl+Z", command=self.text_area.edit_undo)
self.edit_menu.add_command(label="重做", accelerator="Ctrl+Y", command=self.text_area.edit_redo)
self.edit_menu.add_separator()
self.edit_menu.add_command(label="剪切", accelerator="Ctrl+X", command=self.cut)
self.edit_menu.add_command(label="复制", accelerator="Ctrl+C", command=self.copy)
self.edit_menu.add_command(label="粘贴", accelerator="Ctrl+V", command=self.paste)
self.edit_menu.add_separator()
self.edit_menu.add_command(label="全选", accelerator="Ctrl+A", command=self.select_all)
self.menu_bar.add_cascade(label="编辑", menu=self.edit_menu)
self.root.config(menu=self.menu_bar)
def new_file(self, *args):
self.root.title("未命名文件")
self.file_path = None
self.text_area.delete(1.0, tk.END)
def open_file(self, *args):
self.file_path = askopenfilename(defaultextension=".txt", filetypes=[("Text Files", "*.txt"), ("All Files", "*.*")])
if self.file_path:
self.root.title(f"{self.file_path} - 记事本")
self.text_area.delete(1.0, tk.END)
with open(self.file_path, "r") as f:
self.text_area.insert(1.0, f.read())
def save_file(self, *args):
if not self.file_path:
self.save_file_as()
else:
with open(self.file_path, "w") as f:
f.write(self.text_area.get(1.0, tk.END))
def save_file_as(self, *args):
self.file_path = asksaveasfilename(defaultextension=".txt", filetypes=[("Text Files", "*.txt"), ("All Files", "*.*")])
if self.file_path:
self.save_file()
def cut(self, *args):
self.text_area.event_generate("<<Cut>>")
def copy(self, *args):
self.text_area.event_generate("<<Copy>>")
def paste(self, *args):
self.text_area.event_generate("<<Paste>>")
def select_all(self, *args):
self.text_area.tag_add("sel", "1.0", tk.END)
if __name__ == "__main__":
root = tk.Tk()
notepad = Notepad(root)
root.mainloop()
```
这个记事本可以进行基本的文件操作,包括新建、打开、保存和另存为。同时也支持基本的编辑操作,包括撤销、重做、剪切、复制、粘贴和全选。
阅读全文