Python做一个记事本
·
用 Python 制作一个简易的记事本工具,核心是实现文本的新建、打开、保存、编辑等基础功能,同时要有可视化的操作界面。下面我会给你一个基于tkinter(Python 内置 GUI 库)的完整记事本代码,无需额外安装依赖,开箱即用。
完整代码实现
python
运行
import tkinter as tk
from tkinter import filedialog, messagebox
import os
class Notepad:
def __init__(self, root):
# 初始化主窗口
self.root = root
self.root.title("简易记事本 - 未命名")
self.root.geometry("800x600") # 默认窗口大小
# 初始化文件路径变量(记录当前编辑的文件)
self.file_path = None
# 创建文本编辑区域
self.text_area = tk.Text(self.root, wrap=tk.WORD, font=("Consolas", 12))
self.text_area.pack(expand=True, fill="both") # 占满整个窗口
# 创建菜单栏
self.create_menu()
# 绑定快捷键
self.bind_shortcuts()
def create_menu(self):
"""创建菜单栏"""
menu_bar = tk.Menu(self.root)
# 文件菜单
file_menu = tk.Menu(menu_bar, tearoff=0)
file_menu.add_command(label="新建", command=self.new_file, accelerator="Ctrl+N")
file_menu.add_command(label="打开", command=self.open_file, accelerator="Ctrl+O")
file_menu.add_command(label="保存", command=self.save_file, accelerator="Ctrl+S")
file_menu.add_command(label="另存为", command=self.save_as_file, accelerator="Ctrl+Shift+S")
file_menu.add_separator()
file_menu.add_command(label="退出", command=self.exit_app, accelerator="Alt+F4")
menu_bar.add_cascade(label="文件", menu=file_menu)
# 编辑菜单(基础功能)
edit_menu = tk.Menu(menu_bar, tearoff=0)
edit_menu.add_command(label="撤销", command=self.undo, accelerator="Ctrl+Z")
edit_menu.add_command(label="重做", command=self.redo, accelerator="Ctrl+Y")
edit_menu.add_separator()
edit_menu.add_command(label="全选", command=self.select_all, accelerator="Ctrl+A")
menu_bar.add_cascade(label="编辑", menu=edit_menu)
# 帮助菜单
help_menu = tk.Menu(menu_bar, tearoff=0)
help_menu.add_command(label="关于", command=self.show_about)
menu_bar.add_cascade(label="帮助", menu=help_menu)
# 配置主窗口菜单栏
self.root.config(menu=menu_bar)
def bind_shortcuts(self):
"""绑定快捷键"""
self.root.bind("<Control-n>", lambda e: self.new_file())
self.root.bind("<Control-o>", lambda e: self.open_file())
self.root.bind("<Control-s>", lambda e: self.save_file())
self.root.bind("<Control-Shift-s>", lambda e: self.save_as_file())
self.root.bind("<Control-z>", lambda e: self.undo())
self.root.bind("<Control-y>", lambda e: self.redo())
self.root.bind("<Control-a>", lambda e: self.select_all())
def new_file(self):
"""新建文件"""
# 检查是否有未保存的内容
if self.check_unsaved_changes():
self.text_area.delete(1.0, tk.END) # 清空文本区域
self.file_path = None
self.root.title("简易记事本 - 未命名")
def open_file(self):
"""打开文件"""
if self.check_unsaved_changes():
# 选择文件(支持txt、py等文本格式)
file_path = filedialog.askopenfilename(
title="打开文件",
filetypes=[("文本文件", "*.txt"), ("Python文件", "*.py"), ("所有文件", "*.*")]
)
if file_path:
try:
with open(file_path, "r", encoding="utf-8") as f:
content = f.read()
self.text_area.delete(1.0, tk.END)
self.text_area.insert(1.0, content)
self.file_path = file_path
self.root.title(f"简易记事本 - {os.path.basename(file_path)}")
except Exception as e:
messagebox.showerror("错误", f"打开文件失败:{str(e)}")
def save_file(self):
"""保存文件"""
if self.file_path:
# 已有文件路径,直接保存
try:
content = self.text_area.get(1.0, tk.END)
with open(self.file_path, "w", encoding="utf-8") as f:
f.write(content)
messagebox.showinfo("提示", "文件保存成功!")
except Exception as e:
messagebox.showerror("错误", f"保存文件失败:{str(e)}")
else:
# 无文件路径,调用另存为
self.save_as_file()
def save_as_file(self):
"""另存为文件"""
file_path = filedialog.asksaveasfilename(
title="另存为",
defaultextension=".txt",
filetypes=[("文本文件", "*.txt"), ("Python文件", "*.py"), ("所有文件", "*.*")]
)
if file_path:
try:
content = self.text_area.get(1.0, tk.END)
with open(file_path, "w", encoding="utf-8") as f:
f.write(content)
self.file_path = file_path
self.root.title(f"简易记事本 - {os.path.basename(file_path)}")
messagebox.showinfo("提示", "文件保存成功!")
except Exception as e:
messagebox.showerror("错误", f"保存文件失败:{str(e)}")
def exit_app(self):
"""退出程序"""
if self.check_unsaved_changes():
self.root.quit()
def undo(self):
"""撤销操作"""
try:
self.text_area.edit_undo()
except tk.TclError:
messagebox.showinfo("提示", "无可撤销的操作")
def redo(self):
"""重做操作"""
try:
self.text_area.edit_redo()
except tk.TclError:
messagebox.showinfo("提示", "无可重做的操作")
def select_all(self):
"""全选文本"""
self.text_area.tag_add(tk.SEL, 1.0, tk.END)
self.text_area.mark_set(tk.INSERT, 1.0)
self.text_area.see(tk.INSERT)
def show_about(self):
"""显示关于信息"""
messagebox.showinfo("关于", "简易记事本 v1.0\n基于Python tkinter开发")
def check_unsaved_changes(self):
"""检查是否有未保存的修改,返回True表示可以继续操作,False表示取消"""
if self.text_area.edit_modified():
result = messagebox.askyesnocancel(
"提示",
"当前文件有未保存的修改,是否保存?"
)
if result is True:
# 保存后继续
self.save_file()
return True
elif result is False:
# 不保存,直接继续
return True
else:
# 取消操作
return False
return True
if __name__ == "__main__":
# 创建主窗口并运行
root = tk.Tk()
app = Notepad(root)
root.mainloop()
代码关键解释
- 核心库:使用 Python 内置的
tkinter库实现 GUI,无需额外安装(Python 默认自带); - 核心功能:
new_file():新建空白文件,清空编辑区;open_file():打开本地文本文件(支持 txt、py 等格式);save_file()/save_as_file():保存 / 另存为文件,默认编码 UTF-8;- 编辑功能:撤销、重做、全选(绑定了常用快捷键);
- 人性化设计:
- 退出 / 新建 / 打开时检查未保存的修改,避免内容丢失;
- 支持中文路径和中文内容(UTF-8 编码);
- 窗口标题随文件名动态变化;
- 运行条件:
- Python 3.x 版本(推荐 3.8 及以上);
- 无需安装额外依赖,直接运行代码即可。
运行效果
- 执行代码后会弹出一个 800×600 的记事本窗口;
- 可通过菜单栏或快捷键操作:
- 新建:Ctrl+N | 打开:Ctrl+O | 保存:Ctrl+S | 另存为:Ctrl+Shift+S;
- 撤销:Ctrl+Z | 重做:Ctrl+Y | 全选:Ctrl+A;
- 编辑内容后未保存时,退出 / 新建 / 打开会提示是否保存。
总结
- 这个记事本基于
tkinter实现,具备新建、打开、保存、编辑、快捷键等核心功能,满足基础文本编辑需求; - 代码加入了异常处理和未保存提示,避免内容丢失,符合日常使用习惯;
- 无需额外安装依赖,Python 环境下直接运行即可,适合新手学习和使用。
更多推荐


所有评论(0)