用python编写一个记事本
时间: 2023-06-03 08:04:06 浏览: 127
好的,我可以为您提供一个使用Python编写的简易记事本,以下是代码:
```python
from tkinter import *
from tkinter.filedialog import askopenfilename, asksaveasfilename
# 创建窗口
root = Tk()
root.title("记事本")
root.geometry("600x600")
# 创建文本框
text_area = Text(root, font=("Helvetica", 12))
text_area.pack(expand=True, fill=BOTH)
# 新建文件
def new_file():
root.title("未命名文件")
text_area.delete("1.0", END)
# 打开文件
def open_file():
filepath = askopenfilename(defaultextension=".txt", filetypes=[("Text Files", "*.txt"), ("All Files", "*.*")])
if not filepath:
return
text_area.delete("1.0", END)
with open(filepath, "r") as input_file:
text = input_file.read()
text_area.insert("1.0", text)
root.title(f"{filepath}")
# 保存文件
def save_file():
filepath = asksaveasfilename(defaultextension=".txt", filetypes=[("Text Files", "*.txt"), ("All Files", "*.*")])
if not filepath:
return
with open(filepath, "w") as output_file:
text = text_area.get("1.0", END)
output_file.write(text)
root.title(f"{filepath}")
# 菜单栏
menu_bar = Menu(root)
# 文件菜单
file_menu = Menu(menu_bar, tearoff=0)
file_menu.add_command(label="新建", command=new_file)
file_menu.add_command(label="打开", command=open_file)
file_menu.add_command(label="保存", command=save_file)
file_menu.add_separator()
file_menu.add_command(label="退出", command=root.quit)
menu_bar.add_cascade(label="文件", menu=file_menu)
# 添加菜单栏
root.config(menu=menu_bar)
root.mainloop()
```
您可以复制上述代码保存为 Python 文件,然后运行即可使用。希望能对您有所帮助!
阅读全文
相关推荐

















