MJ_
MJ_

Reputation: 744

Python tkinter, tkinter.askdirectory() returns the initial default directory when user hits 'cancel' or X out, or Esc the window

No matter what I do, tkinter.filedialog.askdirectory() returns the initial default (current directory) when the Cancel button, or the X close button on the window, or if the user selects Esc. I tried coding the option for an initial directory to C:\, rather than E:\ where the script is saved, to try to control this. However, if Cancel, X, or Esc is selected, it still returns E:\. I also tried adding the root.protocol to force the X to close the entire program, but it did not change the behavior. I initialized the directory with an empty string, which also had no effect. All the documentation, and question/answers I find, simply state that it should return an empty string in these cases. I need this to be true! I cannot see what is wrong here; thanks in advance for any advice. The only hint I have - is I am unsure how tkinter message and file dialogs use, or if they use, the root window. I think this is where I may be losing control...??

I am on Windows 10, using Python 3.7.0.

Here is a toy example of what I have:

import os
import tkinter
import tkinter.filedialog as tkf

class Directory(tkinter.Tk):
    def __init__(self):
            
        self.root = tkinter.Tk()
        self.root.protocol("WM_DELETE_WINDOW", self.root.quit())
        self.root.withdraw()

        self.directory = ""
        
       
    def GetDirectory(self):
        self.directory = os.path.abspath(tkf.askdirectory(master = self.root, initialdir = 'C:\\', title = "Select your Source directory")) 
        print('type directory', type(self.directory), self.directory=="", self.directory)
      
        return self.directory

if __name__ == "__main__":
    app = Directory()
    Directory.GetDirectory(app)

Output after hitting cancel, Esc, or X:

type directory <class 'str'> False E:\

Upvotes: 1

Views: 4434

Answers (1)

jizhihaoSAMA
jizhihaoSAMA

Reputation: 12672

The cause of your problem is you add os.path.abspath() in your askdirectory.

os.path.abspath():Return a normalized absolutized version of the pathname path

Even though it will return "" when you cancel or press "X", but os.path.abspath("") would return the absolute path of current folder.

self.directory = tkf.askdirectory(master=self.root, initialdir='C:\\', title="Select your Source directory")

This just return the absolute path of the folder you select.And when you select nothing, it will return "".

Upvotes: 3

Related Questions