python实现可以保存、可以加粗字体、为文字增加下划线的记事本源码
时间: 2023-11-19 07:04:58 浏览: 196
这里提供一个基于Tkinter库实现的Python记事本源码,支持保存、加粗、下划线等文本样式:
```python
import tkinter as tk
from tkinter import ttk
from tkinter import messagebox
from tkinter.filedialog import asksaveasfilename
class Notepad:
def __init__(self, master):
self.master = master
self.filename = None
self.bold_on = False
self.underline_on = False
self.text = tk.Text(self.master, font=("Calibri", 12))
self.text.pack(fill="both", expand=True)
self.text.tag_configure("bold", font=("Calibri", 12, "bold"))
self.text.tag_configure("underline", font=("Calibri", 12, "underline"))
# 创建菜单栏
self.menu_bar = tk.Menu(self.master)
self.file_menu = tk.Menu(self.menu_bar, tearoff=0)
self.file_menu.add_command(label="新建", command=self.new_file)
self.file_menu.add_command(label="打开", command=self.open_file)
self.file_menu.add_command(label="保存", command=self.save_file)
self.file_menu.add_separator()
self.file_menu.add_command(label="退出", command=self.master.quit)
self.menu_bar.add_cascade(label="文件", menu=self.file_menu)
self.format_menu = tk.Menu(self.menu_bar, tearoff=0)
self.format_menu.add_command(label="加粗", command=self.bold)
self.format_menu.add_command(label="下划线", command=self.underline)
self.menu_bar.add_cascade(label="格式", menu=self.format_menu)
self.master.config(menu=self.menu_bar)
def new_file(self):
self.filename = None
self.master.title("无标题 - 记事本")
self.text.delete(1.0, tk.END)
def open_file(self):
self.filename = askopenfilename(defaultextension=".txt", filetypes=[("Text Files", "*.txt"), ("All Files", "*.*")])
if self.filename:
self.master.title(self.filename + " - 记事本")
self.text.delete(1.0, tk.END)
with open(self.filename, "r") as f:
self.text.insert(1.0, f.read())
def save_file(self):
if not self.filename:
self.filename = asksaveasfilename(defaultextension=".txt", filetypes=[("Text Files", "*.txt"), ("All Files", "*.*")])
if self.filename:
with open(self.filename, "w") as f:
f.write(self.text.get(1.0, tk.END))
messagebox.showinfo("保存", "文件已保存!")
def bold(self):
start = self.text.index(tk.SEL_FIRST)
end = self.text.index(tk.SEL_LAST)
if not self.bold_on:
self.text.tag_add("bold", start, end)
self.bold_on = True
else:
self.text.tag_remove("bold", start, end)
self.bold_on = False
def underline(self):
start = self.text.index(tk.SEL_FIRST)
end = self.text.index(tk.SEL_LAST)
if not self.underline_on:
self.text.tag_add("underline", start, end)
self.underline_on = True
else:
self.text.tag_remove("underline", start, end)
self.underline_on = False
root = tk.Tk()
notepad = Notepad(root)
root.mainloop()
```
这个记事本支持新建、打开、保存文件,以及加粗、下划线等文本样式。你可以根据自己的需要对其进行修改和扩展。
阅读全文