用python的tkinter库写个记事本
时间: 2023-05-20 11:03:31 浏览: 110
好的,以下是一个简单的用 Python 的 tkinter 库编写的记事本:
```python
from tkinter import *
from tkinter.filedialog import asksaveasfilename, askopenfilename
# 创建主窗口
root = Tk()
root.title("记事本")
# 创建文本框
text = Text(root, font=("Helvetica", 12))
text.pack(expand=True, fill=BOTH)
# 创建菜单栏
menu_bar = Menu(root)
root.config(menu=menu_bar)
# 创建文件菜单
file_menu = Menu(menu_bar, tearoff=0)
menu_bar.add_cascade(label="文件", menu=file_menu)
# 打开文件
def open_file(event=None):
file_path = askopenfilename(defaultextension=".txt", filetypes=[("Text Files", "*.txt"), ("All Files", "*.*")])
if file_path:
text.delete(1.0, END)
with open(file_path, "r") as file:
text.insert(END, file.read())
file_menu.add_command(label="打开", accelerator="Ctrl+O", command=open_file)
# 保存文件
def save_file(event=None):
file_path = asksaveasfilename(defaultextension=".txt", filetypes=[("Text Files", "*.txt"), ("All Files", "*.*")])
if file_path:
with open(file_path, "w") as file:
file.write(text.get(1.0, END))
file_menu.add_command(label="保存", accelerator="Ctrl+S", command=save_file)
# 退出
file_menu.add_separator()
file_menu.add_command(label="退出", accelerator="Alt+F4", command=root.quit)
# 创建编辑菜单
edit_menu = Menu(menu_bar, tearoff=0)
menu_bar.add_cascade(label="编辑", menu=edit_menu)
# 撤销
def undo(event=None):
try:
text.edit_undo()
except:
pass
edit_menu.add_command(label="撤销", accelerator="Ctrl+Z", command=undo)
# 重做
def redo(event=None):
try:
text.edit_redo()
except:
pass
edit_menu.add_command(label="重做", accelerator="Ctrl+Y", command=redo)
# 剪切
edit_menu.add_separator()
edit_menu.add_command(label="剪切", accelerator="Ctrl+X", command=lambda: text.event_generate("<Control-x>"))
# 复制
edit_menu.add_command(label="复制", accelerator="Ctrl+C", command=lambda: text.event_generate("<Control-c>"))
# 粘贴
edit_menu.add_command(label="粘贴", accelerator="Ctrl+V", command=lambda: text.event_generate("<Control-v>"))
# 删除
edit_menu.add_command(label="删除", accelerator="Del", command=lambda: text.delete("sel.first", "sel.last"))
# 全选
edit_menu.add_separator()
edit_menu.add_command(label="全选", accelerator="Ctrl+A", command=lambda: text.tag_add("sel", "1.0", "end"))
# 运行主循环
root.mainloop()
```
希望这个记事本对你有所帮助!
阅读全文