6

使用 Tkinter 和 Python 制作文本编辑器

 3 years ago
source link: https://blog.51cto.com/u_15340774/5504991
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

使用 Tkinter 和 Python 制作文本编辑器_Python

在这篇教程中,我们使用 Tkinter 和 Python 在线运行并制作一个可以新建、打开、编辑并保存文本的文本编辑器应用。

我们可以把这个简易的文本编辑器拆分成三个部分:

  1. 打开或编辑文件的​​btn_open​​ 按钮
  2. 保存文件的​​btn_save​​ 按钮
  3. 编写或编辑文件文本的​​txt_edit​​ 输入框

在我们用 Tkinter 绘制的 GUI 中,我们会把两个按钮集中在输入框的左手边,整个应用窗口大约为 800 像素,同时我们也会设置输入框跟随应用窗口大小进行调整。我们的编辑器大概长这样:

使用 Tkinter 和 Python 制作文本编辑器_Python_02

使用 Python 在线运行项目源代码: ​https://3921d9436a-share.lightly.teamcode.com ​

绘制应用基础轮廓

基本上,我们的文本编辑器包含一行两列,比较窄的那一列为按钮,而比较宽的那一列为文本框。我们可以通过 ​​.grid()​​​ 函数来调整大小。同时,我们也可以在 ​​.rowconfigure()​​​ 以及 ​​.columnconfigure()​​​ 中,把应用窗口和文本框的 ​​minsize​​​ 设置为 800,然后将这两个参数的 ​​weight​​ 设置为 1。

为了让两个按钮都安分地待在同一列,我们需要创建一个名为 ​​frm_buttons​​​ 的框架,然后把 ​​btn_open​​​ 的新建、编辑按钮放在上层,​​btn_save​​ 按钮放在下层。

import tkinter as tk

window = 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​​ 为两个按钮之间添加一点间距,以至于按钮之间不会太拥挤。

按钮的框架完成后,我们同样调整一下窗口中的其他元素:

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 在线运行代码。窗口基本上应该在这样:

使用 Tkinter 和 Python 制作文本编辑器_Python_03

添加打开按钮功能

我们的文本编辑器现在已经有模有样了,但我们还需要为按钮添加相应的指令。我们需要让 ​​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 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")

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}")

这个保存按钮的步骤基本上与打开按钮的步骤相似,其中:

  • 第 25 行在所选路径创建一个新的文件。
  • 第 26 行从文本框中通过​​.get()​​​ 提取字符串并存入​​text​​ 变量中。
  • 第 27把​​text​​ 写入文件。

这部分完成后,同样需要在项目头部文件导入 ​​asksaveasfilename()​​:

import tkinter as tk
from tkinter.filedialog import askopenfilename, asksaveasfilename

最后,把 ​​btn_save​​​ 的 ​​command​​​ 参数调整为 ​​save_file​​ 即大功告成!

使用 Python 在线运行项目源代码: ​https://3921d9436a-share.lightly.teamcode.com ​


Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK