如何在Python Tkinter开发的记事本中实现字体样式与字号调整功能
Tkinter记事本字体大小与样式功能修复方案
核心问题
原代码存在以下问题导致功能无法生效:
- 字体大小设置仅将值写入本地文件,未实际更新文本编辑区的字体属性
- 字体样式功能完全未实现,且对应菜单错误绑定了粘贴功能
- 弹出的设置窗口错误使用
Tk()创建新的主窗口实例,会导致程序逻辑异常 - 没有输入校验,用户输入非数字的字体大小时会触发程序崩溃
- 文件读写未指定编码,打开中文文件时容易出现乱码
完整修改后代码
from tkinter import * import tkinter.messagebox as mb from tkinter.filedialog import askopenfilename, asksaveasfilename import os # 全局存储当前字体配置 current_font_family = "lucida" current_font_size = 20 def newFile(): global file root.title("未命名 - 记事本") file = None textArea.delete(1.0, END) def openFile(): global file file = askopenfilename(defaultextension=".txt", filetypes=[("所有文件", "*.*"), ("文本文档", "*.txt")]) if file == "": file = None else: root.title(os.path.basename(file) + " - 记事本") textArea.delete(1.0, END) f = open(file, encoding="utf-8") textArea.insert(1.0, f.read()) f.close() def save(): global file if file == None: file = asksaveasfilename(initialfile="未命名.txt", defaultextension=".txt", filetypes=[("所有文件", "*.*"), ("文本文档", "*.txt")]) if file == "": file = None else: f = open(file, "w", encoding="utf-8") f.write(textArea.get(1.0, END)) f.close() root.title(os.path.basename(file) + " - 记事本") else: f = open(file, "w", encoding="utf-8") f.write(textArea.get(1.0, END)) f.close() def quitFile(): root.destroy() def cut(): textArea.event_generate(("<<Cut>>")) def copy(): textArea.event_generate(("<<Copy>>")) def paste(): textArea.event_generate(("<<Paste>>")) def info(): mb.showinfo("关于记事本", '''记事本 版本 - 1.1.1 开发者 - Sourabh Sontakke''') def changeSize(): global current_font_size input_size = size.get().strip() # 输入校验 if not input_size.isdigit(): mb.showerror("输入错误", "请输入有效的正整数作为字体大小") return current_font_size = int(input_size) # 实时更新文本框字体 textArea.config(font=(current_font_family, current_font_size)) # 保留原写入文件的逻辑 with open('size.txt', 'w', encoding="utf-8") as f: f.write(str(current_font_size)) def changeSizeWindow(): global size # 用Toplevel创建子窗口,不要重复创建Tk主窗口 TextSize = Toplevel(root) TextSize.geometry("400x300") TextSize.title("修改字体大小") size = StringVar() Label(TextSize, text="输入你想要的字体大小:", font="lucida 15 bold").pack(pady=20) Entry(TextSize, textvariable=size, font="lucida 15").pack(padx=40, pady=10) Button(TextSize, text="应用", command=changeSize, font="lucida 12").pack(pady=20) def changeStyle(): global current_font_family input_style = style.get().strip() if not input_style: mb.showerror("输入错误", "请输入有效的字体名称") return current_font_family = input_style textArea.config(font=(current_font_family, current_font_size)) def changeStyleWindow(): global style styleWindow = Toplevel(root) styleWindow.geometry("400x300") styleWindow.title("修改字体样式") style = StringVar() Label(styleWindow, text="输入你想要的字体名称:\n例如:微软雅黑、Consolas、黑体", font="lucida 15 bold").pack(pady=20) Entry(styleWindow, textvariable=style, font="lucida 15").pack(padx=40, pady=10) Button(styleWindow, text="应用", command=changeStyle, font="lucida 12").pack(pady=20) if __name__ == "__main__": root = Tk() root.title("未命名 - 记事本") root.geometry("600x400") ScrollBar = Scrollbar(root) ScrollBar.pack(fill=Y, side=RIGHT) textArea = Text(root, font=(current_font_family, current_font_size), yscrollcommand=ScrollBar.set) file = None textArea.pack(expand=True,fill="both") ScrollBar.config(command=textArea.yview) MenuBar = Menu(root) FileMenu = Menu(MenuBar, tearoff=0) FileMenu.add_command(label="新建文件", command=newFile) FileMenu.add_command(label="打开文件", command=openFile) FileMenu.add_command(label="保存", command=save) FileMenu.add_separator() FileMenu.add_command(label="退出", command=quitFile) MenuBar.add_cascade(label="文件", menu=FileMenu) EditMenu = Menu(MenuBar, tearoff=0) EditMenu.add_command(label="剪切", command=cut) EditMenu.add_command(label="复制", command=copy) EditMenu.add_command(label="粘贴", command=paste) EditMenu.add_command(label="字体大小", command=changeSizeWindow) EditMenu.add_command(label="字体样式", command=changeStyleWindow) MenuBar.add_cascade(label="编辑", menu=EditMenu) HelpMenu = Menu(MenuBar, tearoff=0) HelpMenu.add_command(label="关于", command=info) MenuBar.add_cascade(label="帮助", menu=HelpMenu) root.config(menu=MenuBar) root.mainloop()
功能说明
- 字体大小修改:点击顶部菜单栏「编辑」-「字体大小」,输入正整数后点击应用即可实时修改全文的字体大小
- 字体样式修改:点击顶部菜单栏「编辑」-「字体样式」,输入系统已安装的字体名称后点击应用即可实时生效
- 新增输入校验,输入非法值时会弹出错误提示,不会导致程序崩溃
- 优化了文件读写的编码配置,避免中文乱码问题
- 所有界面文本已翻译为中文,符合中文用户使用习惯
内容的提问来源于stack exchange,提问作者Sourabh Sontakke
相关产品推荐
相关产品推荐

