另存为文件对话框 - 如何不允许覆盖

zel*_*ite 5 python tkinter python-3.x

我正在尝试在tkinter中创建一个savefile对话框.我需要保存文件名以便以后使用.但是,我不希望filedialog接受选择已存在的文件名.

到目前为止我只有这个:

from tkinter import filedialog

my_file = filedialog.asksaveasfilename(defaultextension = ".myfile", 
                                       filetypes = [("MY SUPER FILE", ".myfile"), 
                                                    ("All files", ".*")])
Run Code Online (Sandbox Code Playgroud)

一种可能性是获取文件名,检查文件名是否存在(使用os.path.isfile),如果已存在具有相同名称的文件,则再次询问用户新名称.但是,tkinter filedialog会询问用户"文件是否已存在.是​​否要覆盖?".因此,如果稍后我告诉用户我不接受文件名选择,这似乎令人困惑.有没有办法强制tkinter filedialog不要求用户覆盖?

编辑:根据答案中的建议,我尝试创建自己的保存文件对话框.

我基本上只在tkinter保存对话框中添加了一个警告:

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)
Run Code Online (Sandbox Code Playgroud)

所以,它看起来很简单.然后我想:我需要创建自己的asksaveasfilename功能.我去检查来源:

def asksaveasfilename(**options):
"Ask for a filename to save as"

return SaveAs(**options).show()
Run Code Online (Sandbox Code Playgroud)

嗯..我需要看看SaveAs做了什么.

class SaveAs(_Dialog):
    "Ask for a filename to save as"

    command = "tk_getSaveFile"
Run Code Online (Sandbox Code Playgroud)

Aaannddd ......我迷路了.我不明白这些碎片是如何组合在一起的.'SaveAs'只有命令tk_getSaveFile.SaveFileDialog如何在这里使用?我怎样才能创造自己的myasksaveasfilename功能?

Aar*_*lla 5

没有这样的选择.如果你想摆脱安全问题,那么你将不得不编写自己的文件对话框.

如果你看一下filedialog.py,你会发现对话框是用Python实现的.因此,您所要做的就是扩展类SaveFileDialogok_command()使用不允许选择现有文件名的方法覆盖该方法.

您可以使用大多数现有代码,只需更改一些文本即可实现目标.

我没有测试过,但这段代码应该可以工作:

def ok_command(self):
        file = self.get_selection()
        if os.path.exists(file):
            if os.path.isdir(file):
                self.master.bell()
                return
            d = Dialog(self.top,
                       title="Overwrite Existing File",
                       text="You can't overwrite an existing file %r. Please select a new name." % (file,),
                       bitmap='error',
                       default=0,
                       strings=("OK",))
            return
        else:
            head, tail = os.path.split(file)
            if not os.path.isdir(head):
                self.master.bell()
                return
        self.quit(file)
Run Code Online (Sandbox Code Playgroud)