TKinter return file type from save dialogue?

Question:

Using TKinter is there a way to know what file type was chosen in a asksaveasfilename or a askopenfilename? I would like to perform a different operation according to the file type that was selected.

Here is my solution, but its has shortcomings:

from pathlib import Path
from tkinter.filedialog import asksaveasfilename
from tkinter.messagebox import showerror

file_path = asksaveasfilename(filetypes=(("Image file", '*.jpg'),
                                         ("Text file", '*.txt')))
if file_path:
    if Path(file_path).suffix == '.jpg':
        print("Image")
    elif Path(file_path).suffix == '.txt':
        print("Text")
    else:
        showerror("Save", "Unknown extension '{}'.".format(Path(file_path).suffix))
Asked By: Morgoth

||

Answers:

Using TKinter is there a way to know what file type was chosen in a asksaveasfilename or a askopenfilename

No, there is not. The dialog has no type information to share. The file types that you specify are merely a filter for the user, which the user is free to use or ignore. The only information you can get from the dialog is whether the user picked a file or not, and the path of the file they picked. There is no other information you can get from the dialog.

Answered By: Bryan Oakley

I know that this question is a long time ago but this answer, in case, for future generation, I found this:

from pathlib import Path 
from tkinter.filedialog import asksaveasfilename 
from tkinter.messagebox import showerror
    
file_type=(("Image file", '.jpg'), ("Text file", '.txt'))
file_path=asksaveasfilename(filetype=file_type, defaultextension=file_type)
print(Path(file_path).suffix)

I get the file type based on which file_type I chose.

my python code

File dialog

Proof

Result

Answered By: B_J
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.