2

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.

Ted Klein Bergman
  • 9,146
  • 4
  • 29
  • 50
Gurdish
  • 89
  • 1
  • 7
  • Consider printing the value to see what it is in case of a cancel – mousetail Jan 20 '22 at 10:41
  • I have, the 2 print statements at the bottom indicate a period when the user clicks "Cancel". However this doesn't return the correct message in the IF. – Gurdish Jan 20 '22 at 10:42
  • @Bryan Oakley So how do you catch it? If I change it to an empty string, it still doesn't work – Gurdish Jan 20 '22 at 10:48
  • You print No folder selected if the user selects the current folder, that's what `if outputfolder == '.':` does –  Jan 20 '22 at 10:49

1 Answers1

2

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)
Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685