3def open_file(): """Open a file for editing.""" filepath = askopenfilename( filetypes=[("Text Files", "*.txt"), ("All Files", "*.*")] ) if not filepath: return txt_edit.delete("1.0", tk.END) with open(filepath, mode="r", encoding="utf-8") as input_file: text = input_file.read() txt_edit.insert(tk.END, text) window.title(f"Simple Text Editor - {filepath}")
这些步骤完成后,我们还需要在项目头部添加 import askopenfilename() from tkinter.filedialog,然后把 btn_opn 的 command 参数设置为 open_file:
import tkinter as tk from tkinter.filedialog import askopenfilename
def open_file(): """Open a file for editing.""" filepath = askopenfilename( filetypes=[("Text Files", "*.txt"), ("All Files", "*.*")] ) if not filepath: return txt_edit.delete("1.0", tk.END) with open(filepath, mode="r", encoding="utf-8") as input_file: text = input_file.read() txt_edit.insert(tk.END, text) window.title(f"Simple Text Editor - {filepath}")
window = tk.Tk() window.title("Simple Text Editor")
def save_file(): """Save the current file as a new file.""" filepath = asksaveasfilename( defaultextension=".txt", filetypes=[("Text Files", "*.txt"), ("All Files", "*.*")], ) if not filepath: return with open(filepath, mode="w", encoding="utf-8") as output_file: text = txt_edit.get("1.0", tk.END) output_file.write(text) window.title(f"Simple Text Editor - {filepath}")
这个保存按钮的步骤基本上与打开按钮的步骤相似,其中:
第 25 行在所选路径创建一个新的文件。
第 26 行从文本框中通过.get() 提取字符串并存入text 变量中。
第 27行把text 写入文件。
这部分完成后,同样需要在项目头部文件导入 asksaveasfilename():
import tkinter as tk from tkinter.filedialog import askopenfilename, asksaveasfilename