まとめてトライ
tkinter上で、下記事項をまとめて実施した記録。
- ドラッグ&ドロップ
- 2つのファイルDiff(差分)
- HTML表示
任意のファイル2つをtkinterで作成されたWindowにドラッグ&ドロップし、その差分(HTML with CSS)をWindowに表示するものである。
最初に結果
difflibで出力されるHTML(with CSS)形式を、tkinterwebを使って表示する。
ソースコード+解説
import os
import difflib # HTML形式のdiff出力用
import tkinter as tk
import tkinterdnd2 as tkdnd # tkinter上でDrag&Drop利用
from tkinterweb import HtmlFrame # HTMLをtkinter作成Windowに表示用
def DiffDisplay(event): # Drag&Drop時にCallされる関数
if event.data:
frame.load_html("<html></html>") # 表示をHTMLにて空にする
file1_path = event.data.split()[0] # 1番目ファイルのPath取得
file2_path = event.data.split()[1] # 2番目ファイルのPath取得(3番目以降は無視)
file1 = open(file1_path) # 1番目ファイルOpen
file2 = open(file2_path) # 2番目ファイルOpen
diff = difflib.HtmlDiff() # difflibによりHTML(with CSS)形式のdiff出力
cur_path = os.getcwd() # 起動ディレクトリ取得
output_name = 'diff.html' # 結果ファイル
output_path = os.path.join(cur_path, output_name) # 結果ファイルのPath作成
output = open(output_path, 'w') # 結果ファイルOpen
output.writelines(diff.make_file(file1, file2)) # 結果ファイルへHTML書き出し
file1.close() # 1番目ファイルClose
file2.close() # 2番目ファイルClose
output.close() # 結果ファイルClose
root.title('Diff: ' + file1_path + ' ' + file2_path) # Windowタイトルにファイル名を入れる
frame.load_file(output_path) # 結果ファイルHTMLをWindowに表示
return event.action
##### Main ######
root = tkdnd.TkinterDnD.Tk() # Drag&Drag用の設定
root.drop_target_register(tkdnd.DND_FILES) # Drag&Drag用の設定
root.title("Diff 2 Files") # Windowタイトル(初期値)
root.geometry("800x400") # Windowサイズ
root.dnd_bind('<<Drop>>', DiffDisplay) # Drag&Dragが行われたときにCallされる関数(DiffDisplay)の定義
frame = HtmlFrame(master=root, horizontal_scrollbar="auto", messages_enabled = False) # WindowをHTMLフレーム対応とする(横スクロールバー付き、縦スクロールは自動的に対応する様子)
frame.pack() # フレーム表示
root.mainloop()
なお、ファイルが1つしかDrag&Dropされなかったときの状況などのエラー処理は考慮していない。
EOF