在这篇教程中,我们使用 Tkinter 和 Python 在线运行并制作一个可以新建、打开、编辑并保存文本的 文本编辑器应用。
我们可以将这个简单的文本编辑器分成三个部分:
[En]
We can split this simple text editor into three parts:
- 打开或编辑文件的
​btn_open​
按钮 - 保存文件的
​btn_save​
按钮 - 编写或编辑文件文本的
​txt_edit​
输入框
在我们用 Tkinter 绘制的 GUI 中,我们会把两个按钮集中在输入框的左手边,整个应用窗口大约为 800 像素,同时我们也会设置输入框跟随应用窗口大小进行调整。我们的编辑器大概长这样:
使用 Python 在线运行项目源代码:https://3921d9436a-share.lightly.teamcode.com
绘制应用基础轮廓
基本上,我们的文本编辑器包含一行两列,比 较窄的那一列为按钮,而比 较宽的那一列为文本框。我们可以通过 ​.grid()​
函数来调整大小。同时,我们也可以在 ​.rowconfigure()​
以及 ​.columnconfigure()​
中,把应用窗口和文本框的 ​minsize​
设置为 800,然后将这两个参数的 ​weight​
设置为 1。
为了让两个按钮都安分地待在同一列,我们需要创建一个名为 ​frm_buttons​
的框架,然后把 ​btn_open​
的新建、编辑按钮放在上层, ​btn_save​
按钮放在下层。
import tkinter as tkwindow = tk.Tk()window.title("Text Editor")window.rowconfigure(0, minsize=800, weight=1)window.columnconfigure(1, minsize=800, weight=1) txt_edit = tk.Text(window)frm_buttons = tk.Frame(window, relief=tk.RAISED, bd=2)btn_open = tk.Button(frm_buttons, text="Open")btn_save = tk.Button(frm_buttons, text="Save As...")
- 第 1 行导入
​tkinter​
- 第 3、4 行创建名为
​"文本编辑器"​
的新窗口 - 第 6、7 行设置窗口行列参数
- 第 9-12 行创建文本框、按钮框架以及两个所需的按钮。
设置按钮
基本设置完成后,我们可以使用 ​.grid()​
函数为两个按钮进行设置:
btn_open.grid(row=0, column=0, sticky="ew", padx=5, pady=5)btn_save.grid(row=1, column=0, sticky="ew", padx=5)
这两行简单的代码会在按钮框架中创建一个两行一列的网格,而我们为 ​btn_open​
及 ​btn_save​
两个按钮的 ​sticky​
参数设置为 ​"ew"​
,强制这两个按钮 横向填满整个框,以确保按钮的大小相同。然后,我们也通过 ​padx​
和 ​pady​
为两个按钮之间添加一点间距,以至于按钮之间不会太拥挤。
在按钮的框架完成后,我们还调整窗口中的其他元素:
[En]
After the frame of the button is complete, we also adjust the other elements in the window:
frm_buttons.grid(row=0, column=0, sticky="ns")txt_edit.grid(row=0, column=1, sticky="nsew")
这两行代码和上一段相似,但这时在窗口中创建一个一行两列的网格。我们把 ​frm_buttons​
写在 ​txt_edit​
上方,那样展示的效果就会是按钮在左,文本框在右。
我们把按钮列的 ​sticky​
参数设置为 ​"ns"​
,让按钮列 竖向填满,而文本框的 ​sticky​
参数设置为 ​"nsew"​
,让它 填满四周。
基本框架完成后,我们可以在项目下方添加 ​window.mainloop()​
函数并使用 Python 在线运行代码。窗口基本上应该在这样:
添加打开按钮功能
我们的文本编辑器现在已经有模有样了,但我们还需要为按钮添加相应的指令。我们需要让 ​btn_open​
具有打开文件对话的功能,让用户打开文件后将文本展示在 ​txt_edit​
的文本框中。
import tkinter as tk 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}")
- 第 5 – 7 行使用
​tkinter.filedialog​
模块中的​askopenfilename()​
对话来打开文件对话框,然后将路径保存到​filepath​
中。 - 第 8、9 行检查用户是否关闭对话框或选择取消,如是则
​filepath​
为​None​
。 - 第 10 行使用
​.delete()​
命令清楚文本框中现有的内容。 - 第 11、12 行打开并使用
​.read()​
读取相关内容并把文本保存为字符串。 - 第 13 行使用
​.insert()​
将字符串插入文本框。 - 第 14 行修改窗口的标题,让窗口标题包含文件名称。
这些步骤完成后,我们还需要在项目头部添加 ​import askopenfilename() from tkinter.filedialog​
,然后把 ​btn_opn​
的 ​command​
参数设置为 ​open_file​
:
import tkinter as tkfrom tkinter.filedialog import askopenfilenamedef 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")window.rowconfigure(0, minsize=800, weight=1)window.columnconfigure(1, minsize=800, weight=1)txt_edit = tk.Text(window)frm_buttons = tk.Frame(window, relief=tk.RAISED, bd=2)btn_open = tk.Button(frm_buttons, text="Open", command=open_file)btn_save = tk.Button(frm_buttons, text="Save As...")
添加保存按钮功能
打开按钮完成后,我们还需要为保存按钮添加相应的功能。我们需要让 ​btn_save​
打开保存文件对话框,通过 ​tkinter.filedialog​
模块中的 ​asksaveasfilename()​
功能,提取文本框中的文本并写入相应的路径。
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}")
保存按钮的步骤与打开按钮的步骤基本相似,其中:
[En]
The step of saving the button is basically similar to the step of opening the button, where:
- 第 25 行在所选路径创建一个新的文件。
- 第 26 行从文本框中通过
​.get()​
提取字符串并存入​text​
变量中。 - 第 27 行把
​text​
写入文件。
这部分完成后,同样需要在项目头部文件导入 ​asksaveasfilename()​
:
import tkinter as tkfrom tkinter.filedialog import askopenfilename, asksaveasfilename
最后,把 ​btn_save​
的 ​command​
参数调整为 ​save_file​
即大功告成!
使用 Python 在线运行项目源代码:https://3921d9436a-share.lightly.teamcode.com
Original: https://blog.51cto.com/u_15340774/5504991
Author: TeamCode
Title: 使用 Tkinter 和 Python 制作文本编辑器
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/513297/
转载文章受原作者版权保护。转载请注明原作者出处!