在 Tkinter 中捕获 "Cancel"

Catching "Cancel" in Tkinter

我有一个脚本,可以在执行其他任务之前打开 window 提示,让用户进入 select 目录。如果用户selects“取消”,我希望程序显示适当的消息并退出程序。

但是,我无法让它工作。这是我尝试过的:

import tkinter as tk
import pathlib
from tkinter import filedialog

print('\nScript Initialised\nOpening File Dialog Window...\n')
# Define Functions here
def chooseDir():
    print('Choose folder 1')
    global outputfolder
    outputfolder = pathlib.Path(filedialog.askdirectory(title="Output Folder", initialdir='C:\'))
    if outputfolder == '.':
        print('No folder selected. Program exiting.')
        quit()
    root.withdraw()

def openFile():
    print('Choose folder 2')
    global inputfolder
    inputfolder = pathlib.Path(filedialog.askdirectory(title="Import Folder", initialdir='C:\'))
    if inputfolder == '.':
        print('No folder selected. Program exiting.')
        quit()
    root.withdraw()

# Create Tkinter menu
root = tk.Tk()
root.withdraw()
openFile()
root.withdraw()
chooseDir()
root.destroy()
root.mainloop()

print(outputfolder)
print(inputfolder)

我也试过一个空字符串 '' 并且它似乎没有在 if 语句中打印消息。

askdirectory 的定义行为是 return 如果您按取消键则为空字符串。你需要检查一下。您正在做的是在进行检查之前将该空字符串转换为 Path 对象。在确认它不是空字符串之前,您不应该这样做。

path = filedialog.askdirectory(title="Output Folder", initialdir='C:\')
if path == "":
    print("No folder selected. Program exiting.")
    quit()
outputfolder = pathlib.Path(path)