在Python中处理按钮事件时出现的问题

时间:2018-07-26 12:28:01

标签: python tkinter event-handling

如何在Python中处理按钮单击事件?我是python的新手,正在尝试开发Zip Extractor工具。我已经正确处理了Btn1​​和Btn2,但是第3个却给了我错误。(“名称res1未定义”)这是代码 我写了以下内容:请帮助我,因为我是noobie:|谢谢Adv:)

from tkinter import *
from tkinter.filedialog import askdirectory
import os, zipfile

extension = ".zip"
PASSWORD = "virus007"

global res1
global res2

window = Tk()

window.title("Welcome Zip_Extractor_Utility")

window.geometry('640x260')

lbl1 = Label(window, text="Select Source Location:" ,font=("Arial Bold", 12))

lbl2 = Label(window, text="Select Destination Location:" ,font=("Arial Bold", 12))

lbl1.grid(column=0, row=7)

lbl2.grid(column=50, row=7)

def clicked1():
 res1 = askdirectory()
 print(res1)
 return res1

btn1 = Button(window, text="Browse" , command=clicked1)

btn1.grid(column=1, row=7)

def clicked2():
 res2 = askdirectory()
 print(res2)
 return res2

btn2 = Button(window, text="Browse" , command=clicked2)

btn2.grid(column=51, row=7)

##lbl3 = Label(window, text="Extract:" ,font=("Arial ", 12))
##lbl3.grid(column=70, row=7)

def clicked3():
    os.chdir(res1) # change directory from working dir to dir with files
    for item in os.listdir(res1): # loop through items in dir
            if item.endswith(extension): # check for ".zip" extension
                file_name = os.path.abspath(item) # get full path of files
                zip_ref = zipfile.ZipFile(file_name) # create zipfile object
                zip_ref.setpassword(PASSWORD)
                zip_ref.extractall(res2) # extract file to dir
                zip_ref.close() # close file
                #os.remove(file_name) # delete zipped file
    print('done')



btn3 = Button(window, text="Extract" , command=clicked3) 
btn3.grid(column=71, row=7)

window.mainloop()

1 个答案:

答案 0 :(得分:0)

对于您而言,只需检查res1函数中是否定义了res2clicked3。也许使用'res1' in vars() and 'res2' in vars()。如果未定义,请警告用户他们需要首先指定源文件夹和目标文件夹。