问题
I have a saving routine that should prompt the user in the following way:
- If the currently selected file name exists, prompt for overwrite
- If the currently selected file name is empty (i.e. ""), set up a dialog to ask user to insert file name
- If the currently selected file name does not exist, save it!
My code is currently like below, but I feel like there should be a better way of doing this. As it is now the user is prompted with a dialog with choices "Yes, No, Cancel", but I would want it to be "Yes, Save as, Cancel". I really could not find any way to change the "No" button to a "Save as" button that opens a dialog where the user can insert the wanted file name. Any suggestions of improving this?
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
UPDATE
The code was successfully changed to:
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:
You're using the wrong dialog type. Use FileDialog instead:
- It already includes the "prompt for a confirmation if a file will be overwritten" feature with
wx.FD_OVERWRITE_PROMPT
- That's what everyone else uses so users will expect this kind of dialog and be confused when they get something else
I couldn't find a way to replace "Save" with "Save as" in the dialog (it just has wx.FD_SAVE
) but most people won't notice that.
来源:https://stackoverflow.com/questions/14524525/implement-save-as-in-save-dialog-wxpython