I'm trying to make a savefile dialog in tkinter. I need to save the file name to use later. However, I do not want the filedialog to accept selecting an already existing file name.
So far I only have this:
from tkinter import filedialog
my_file = filedialog.asksaveasfilename(defaultextension = ".myfile",
filetypes = [("MY SUPER FILE", ".myfile"),
("All files", ".*")])
One possibility would be to get the file name, check if it exists (using os.path.isfile) and ask again the user for new name if there is already a file with the same name. However, the tkinter filedialog asks the user "file already exists. do you want to overwrite?". So it seems confusing if later I tell the user that I do not accept the filename choice. Is there a way to force the tkinter filedialog to not ask the user about the overwriting?
Edit: Based on the suggestions in the answers, I tried to make my own save file dialog.
I basically only added a warning to the tkinter save dialog:
class MySaveFileDialog(filedialog.FileDialog):
""" File save dialog that does not allow overwriting of existing file"""
def ok_command(self):
file = self.get_selection()
if os.path.exists(file):
if os.path.isdir(file):
self.master.bell()
return
messagebox.showarning("The current file name already exists. Please give another name to save your file.")
else:
head, tail = os.path.split(file)
if not os.path.isdir(head):
self.master.bell()
return
self.quit(file)
So, it looks pretty simple. Then I thought: I need to create my own asksaveasfilename function.
I went to check the source:
def asksaveasfilename(**options):
"Ask for a filename to save as"
return SaveAs(**options).show()
Humm.. I need to see what is SaveAs doing.
class SaveAs(_Dialog):
"Ask for a filename to save as"
command = "tk_getSaveFile"
Aaannddd... i'm lost. I don't understand how this pieces fit together. 'SaveAs' just has the command tk_getSaveFile. How is the SaveFileDialog being used here? And how can I make my own myasksaveasfilename function?
askokcancelmessage box to give them one last chance before they shoot themself in the foot. :)