Search code examples
wxpython

wxPython FileDialog default filename blank under Windows 10


I want to have a time based file name when saving a log file. When I try to set the default filename, the dialog comes up with a blank filename, as shown below. I have tried the equivalent positional function call and it also does not work.

enter image description here

Any idea how to get wx.FileDialog() to set the filename so that all you need to do is to click "Save" to save the file with the default name?

Using the following versions under Windows 10:

Python 3.8.6 (tags/v3.8.6:db45529, Sep 23 2020, 15:52:53) [MSC v.1927 64 bit (AMD64)]

wx.version: 4.1.1 msw (phoenix) wxWidgets 3.1.5

Code that doesn't work:

def OnSave(self, event):
    default_file = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + ".log"
    dlg = wx.FileDialog(self.frame, message = "Save Log Contents",
                                    defaultDir = os.getcwd(),
                                    defaultFile = default_file,
                                    wildcard = "Log files (*.log)|*.log",
                                    style = wx.FD_SAVE|wx.FD_OVERWRITE_PROMPT)
    if dlg.ShowModal() == wx.ID_CANCEL:
        dlg.Destroy()
        return

    file_path = dlg.GetPath()
    self.window.tc.AppendText("%s  Saving log to %s\n" % (datetime.datetime.now(), file_path))
    self.window.tc.SaveFile(file_path)
    dlg.Destroy()
    return True

Solution

  • You can't have : in your file name. Change this line:

      default_file = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + ".log"
    

    To this:

      default_file = datetime.datetime.now().strftime('%Y-%m-%d %H_%M_%S') + ".log"
    

    And you will get much better results.

    How I discovered this (it wasn't immediate):

    I didn't spot this until I tried setting the default file name with

    dlg.SetFilename(default_file)
    

    prior to opening the dialog, and I got an error message. Then I changed the default filename to 'junk.log' and it worked okay. Then I printed out the default_file to the console and discovered the issue.