[单击按钮时功能运行

问题描述 投票:-1回答:1

我正在使用Python 3.x制作Windows应用程序。我在这里有功能:

def deletefolder(): 
    currentUser=os.getlogin()
    folderPath="C:/users/{username}/appdata/roaming/Strategy Folder/Home/PROFIILE/CACHE".format(username=getpass.getuser())
    shutil.rmtree(folderPath)  
    os.rmdir(folderPath) 

delbtn = Button(deltab, text="Delete Cache", command=deletefolder)
delbtn.pack(pady=20)

[当我去测试它时,它将立即运行“删除文件夹”功能。我希望它在单击按钮时运行。我试图做一个if / then语句,然后有一个标签显示它已经完成。相反,它似乎可以继续运行,并且错误提示文件夹不再存在(因为该代码实际上可以删除该文件夹)。我看过这里的几篇文章,看来if / then可能效果最好。但是,如果它在程序运行的开始时运行,那是不好的,因为它将占用一遍又一遍的资源。

感谢您的帮助。

python-3.x tkinter
1个回答
0
投票
from tkinter import messagebox

并使用try-except:

def deletefolder(): 
    try:
        currentUser=os.getlogin()
        folderPath="C:/users/{username}/appdata/roaming/Strategy Folder/Home/PROFIILE/CACHE".format(username=getpass.getuser())
        shutil.rmtree(folderPath)  
        os.rmdir(folderPath) 
    except Exception:
        messagebox.showinfo('Warning','Folder not exist')
© www.soinside.com 2019 - 2024. All rights reserved.