Python—利用tkiner制作一个文本文件比对小工具

使用tkinter模块写的,非常便捷。二话不说,直接上代码

# -*- coding: utf-8 -*- 
import difflib,webbrowser
import os
import tkinter as tk
from tkinter import filedialog,messagebox 

def readfile(filename):
  try:
    with open(filename,'r+',encoding='utf-8') as f:
      text=f.read().splitlines()    #结果为每行的列表
    return text
  except IOError as error:
    messagebox.showerror('警告',filename+'读取失败'+str(error))

def savediff(file1,file2):
  lines1=readfile(file1)
  lines2=readfile(file2)
  d=difflib.HtmlDiff()
  with open(htmlfile,'w',encoding='UTF-8') as f:
    res=d.make_file(lines1,lines2)
    f.write(res)

def getfile(filepath):
  dirs=os.path.dirname(os.path.abspath(__file__))
  path=filedialog.askopenfilename(title=u'选择文件',initialdir=dirs)
  filepath.set(path)

def compare():
  file1=path1.get()
  file2=path2.get()
  savediff(file1,file2)
  webbrowser.open(htmlfile)   #打开html

if __name__=='__main__':
  window = tk.Tk()
  window.title('文件比对小工具')
  window.geometry('500x400')       # 这里的乘是小x
  window.wm_attributes('-topmost',True)
  path1=tk.StringVar()
  path2=tk.StringVar()
  htmlfile='比对结果.html'
  tk.Button(window,text='打开文件一',command=lambda:getfile(path1)).grid(row=0,column=0,pady=2)
  tk.Entry(window,textvariable=path1,width=40).grid(row=0,column=1)
  tk.Button(window,text='打开文件二',command=lambda:getfile(path2)).grid(row=1,column=0,pady=2)
  tk.Entry(window,textvariable=path2,width=40).grid(row=1,column=1)
  tk.Button(window,text="执行文件比对",command=compare).grid(row=2,column=0,pady=5)
  window.mainloop()

这是执行的效果,打开两个文件,然后点击执行,几秒后就会弹出比对结果的html页面,非常便利
在这里插入图片描述
当然,也可以用pyinstaller打包成exe,就更加便利了

这是我打包好的

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值