在wxpython保存对话框中实现“另存为”

3 投票
1 回答
3555 浏览
提问于 2025-04-17 13:39

我有一个保存文件的程序,它应该以以下方式提示用户:

  • 如果当前选择的文件名已经存在,就提示用户是否要覆盖这个文件
  • 如果当前选择的文件名是空的(也就是""),就弹出对话框让用户输入文件名
  • 如果当前选择的文件名不存在,就直接保存文件!

我现在的代码是这样的,但我觉得应该有更好的方法来实现这个功能。现在用户会看到一个对话框,上面有“是、否、取消”的选项,但我想要的是“是、另存为、取消”。我真的找不到办法把“否”这个按钮改成“另存为”按钮,这样用户可以打开一个对话框来输入想要的文件名。有没有什么建议可以改进这个?

def saveProject(window):

if os.path.exists(window.getGlobalSettings().getCurrentFileName()): #File exists from before   
    dlg = wx.MessageDialog(window,
                "Overwrite existing project file " + window.getGlobalSettings().getCurrentFileName() + "?",
                "Overwrite existing project file",
                wx.SAVE|wx.CANCEL|wx.ICON_QUESTION)

    result = dlg.ShowModal()
    dlg.Destroy()

    if result == wx.ID_YES:
        save(window,currentFileName)
        return True
    elif result == wx.ID_SAVEAS:
        #TODO: do shit here
        return False
    elif result == wx.ID_NO:
        return False
    elif result == wx.ID_CANCEL:
        return False

elif window.getGlobalSettings().getCurrentFileName == "":
    #TODO: do shit here
    return False

else:
    save(window,window.getGlobalSettings().getCurrentFileName())
    return True

更新

代码已经成功修改为:

def saveProject(window):

dlg = wx.FileDialog(window, "Save project as...", os.getcwd(), "", "*.kfxproject", \
                    wx.SAVE|wx.OVERWRITE_PROMPT)
result = dlg.ShowModal()
inFile = dlg.GetPath()
dlg.Destroy()

if result == wx.ID_OK:          #Save button was pressed
    save(window,inFile)
    return True
elif result == wx.ID_CANCEL:    #Either the cancel button was pressed or the window was closed
    return False

1 个回答

2

你用错了对话框类型。应该使用FileDialog

  • 这个对话框已经包含了“如果文件会被覆盖,提示确认”的功能,使用的是wx.FD_OVERWRITE_PROMPT
  • 大家都是用这个,所以用户会期待看到这种对话框,如果看到别的就会感到困惑

我找不到办法把对话框里的“保存”换成“另存为”(它只有wx.FD_SAVE),但大多数人不会注意到这一点。

撰写回答