tkinterでGUIを作った

zipファイルのパスワード解析ソフトを自作してみた - bogamp’s blog
この前作ったpythonのコードにtkinterGUIを追加してみた。

import sys
import pyzipper
from tkinter import *
from tkinter import filedialog
from tkinter import ttk
global zipf
global listf
global caution
zipf = ""
listf = ""
def startcrack():
  flag = 0
  try:
    z = pyzipper.AESZipFile(zipf,"r",compression=pyzipper.ZIP_DEFLATED,encryption=pyzipper.WZ_AES)
  except:
	  res = "エラー"
	  answer(res)
	  sys.exit()
  with open(listf) as file:
    for line in file:
        print(line)
        try:
          z.extractall(pwd=str.encode(line.rstrip()))
          flag = 1
          break
        except:
          pass
    if flag == 1:
      ans = '成功しました。パスワードは\n' + line.rstrip() + '\nです。'
    else:
      ans = 'パスワードを発見できませんでした。'
    answer(ans)
 
def answer(ans):
	answer = Tk()
	answer.title('解析結果')
	frame_ans = ttk.Frame(answer)
	label_ans = ttk.Label(text=ans)
	frame_ans.pack()
	label_ans.pack()
	answer.mainloop()
def caut():
	global caution
	caution = Tk()
	caution.title('エラー')
	frame_caution = ttk.Frame(caution,height=20,width=30)
	label_caution = ttk.Label(text='選択されていない\nファイルがあります',foreground="#ff0000")
	button_caution = ttk.Button(text="OK",command=lambda: [caution.destroy(),main()])
	frame_caution.pack()
	label_caution.pack(side=TOP)
	button_caution.pack(side=TOP)
	caution.mainloop()

def main():
	root= Tk()
	root.title('パスワード解析')
	frame1 = ttk.Frame(root,padding = 50)
	t = StringVar()
	filebutton=ttk.Button(
	    frame1,text='解析するファイルを選ぶ',command=lambda: filebutton_clicked())
	listbutton=ttk.Button(
       frame1,
       text='パスワードリストを選ぶ',
       command=lambda: listbutton_clicked())
	button1=ttk.Button(
       frame1,
       text='実行',
       command=lambda: print(button1_clicked(root)))
	frame1.pack()
	filebutton.pack(side=TOP)
	listbutton.pack(side=TOP)
	button1.pack(side=TOP)
	root.mainloop()
	
def filebutton_clicked():
    global zipf
    zipf = filedialog.askopenfilename(initialdir='~/')
def listbutton_clicked():
	 global listf
	 listf = filedialog.askopenfilename(initialdir='~/')
def button1_clicked(root):
	if zipf == "" or listf == "":
		 root.destroy()
		 caut()
	else:
		root.destroy()
		startcrack()
		
main()

処理中に「処理中です」みたいな画面を出すには、threadingで並行処理する必要があるらしい。面倒なので無しにした。
グローバル変数に頼りすぎかも?ちゃんと作るならオブジェクト指向的な書き方をするべきなのかもしれない。

しかしGUIを作るのってけっこう面倒ですね…