Tkinter Askopenfilename Not Returning As Expected When User Clicks "Cancel."
Solution 1:
Didn't see this post till after I answered an older but similar question!
Basically, clicking Cancel will return an empty string...
Unless you actually select/highlight a file first and then click cancel.
This seems to return an empty tuple!!!
(I didn't try with initialdir and initialfile options but am guessing they also cause an empty tuple to be returned... at least initially?)
Using python 2.6.6 (IDK, ask RedHat)
Running the following code produces the subsequent results
f_picked = tkFileDialog.askopenfilename()
test = type(f_picked)
print (test)
Results:
<type 'unicode'>
# Nothing selected, Cancel clicked
<type 'tuple'>
# File selected, Cancel clicked
<type 'str'>
# File selected, OK clicked
<type 'tuple'>
# Multiple files selected, OK clicked
Solution 2:
I have a File -> Open
menu item that displays an askopenfilename dialogue. I am finding that with python 2.7
and 3.6
, the first time I use the dialogue and select Cancel
or close the dialogue from the window border, it returns an empty tuple instead of ''
. Every time thereafter the dialogue returns ''
on Cancel
or window close.
Perhaps this is some sort of feature but it feels like a bug, particularly for this dialogue that doesn't support selection of multiple files. An empty tuple would make sense from askopenfilenames.
I've settled on this simple test and cleanup for the file name returned by the askopenfilename dialogue:
if str(filename) == '()':
filename = ''
Solution 3:
Hmm... Make sure you are using using Python 3 because this won't work on Python 2 It worked for me, when I changed the brackets to "" (i'm on Python 2)
Post a Comment for "Tkinter Askopenfilename Not Returning As Expected When User Clicks "Cancel.""