用python写一段代码,在windows上运行,使用tkinter,用于比较两段很长的文本content1和content2的差异,content1可加载指定路径的文件。程序能够在可视化界面上展示差异项,展示的窗口分为左界面和右界面,左界面显示content1,右界面显示content2,左界面和右界面内容中,存在差异的部分,用颜色进行标记。
时间: 2024-03-13 21:45:45 浏览: 104
好的,我来为您编写这段代码。
```python
import tkinter as tk
import difflib
class DiffViewer:
def __init__(self, master):
self.master = master
master.title("Diff Viewer")
# 创建左右两个文本框和滚动条
scrollbar1 = tk.Scrollbar(master)
scrollbar1.pack(side=tk.RIGHT, fill=tk.Y)
self.text1 = tk.Text(master, yscrollcommand=scrollbar1.set, width=50)
self.text1.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
scrollbar1.config(command=self.text1.yview)
scrollbar2 = tk.Scrollbar(master)
scrollbar2.pack(side=tk.RIGHT, fill=tk.Y)
self.text2 = tk.Text(master, yscrollcommand=scrollbar2.set, width=50)
self.text2.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
scrollbar2.config(command=self.text2.yview)
# 创建比较按钮
button = tk.Button(master, text="Compare", command=self.compare)
button.pack()
def compare(self):
content1 = self.load_file() # 加载文件
content2 = self.text2.get("1.0", tk.END) # 获取文本框2的内容
# 使用difflib库进行比较
diff = difflib.ndiff(content1.splitlines(), content2.splitlines())
# 用颜色进行标记不同之处
self.text1.delete("1.0", tk.END)
self.text2.delete("1.0", tk.END)
for line in diff:
if line.startswith("+"):
self.text2.insert(tk.END, line[2:] + "\n", "added")
elif line.startswith("-"):
self.text1.insert(tk.END, line[2:] + "\n", "deleted")
else:
self.text1.insert(tk.END, line + "\n")
self.text2.insert(tk.END, line + "\n")
self.text1.tag_config("deleted", foreground="red")
self.text2.tag_config("added", foreground="green")
def load_file(self):
# 打开文件选择对话框
filepath = tk.filedialog.askopenfilename()
if filepath:
# 读取文件内容
with open(filepath, "r", encoding="utf-8") as f:
content = f.read()
# 在文本框1中显示文件内容
self.text1.delete("1.0", tk.END)
self.text1.insert(tk.END, content)
return content
else:
return ""
root = tk.Tk()
app = DiffViewer(root)
root.mainloop()
```
运行以上代码,会弹出一个窗口,左边显示加载的文件内容,右边可以手动输入文本内容,点击“Compare”按钮会比较两个文本的异同,并将不同之处用颜色标记。
阅读全文