pythontkinterpathlibfiledialog

Catching "Cancel" in Tkinter


I have a script that opens a prompt window for a user to select a directory before performing some other tasks. If the user selects "Cancel", I want the program to display an appropriate message and exit the program.

However, I cannot get this to work. Here is what I've tried:

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)

I've also tried an empty string of '' and that doesn't appear to print the message in the if-statement.


Solution

  • The defined behavior of askdirectory is to return the empty string if you press cancel. You need to check for that. What you're doing instead is converting that empty string to a Path object before doing the check. You shouldn't do that until after you've verified that it's not the empty string.

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