Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading