0

My wxpython GUI has a method for opening a FileDialog:

def open_filedlg(self,event):
    dlg = wx.FileDialog(self, "Choose XYZ file", getcwd(), "",
             "XYZ files (*.dat)|*.dat|(*.xyz)|*.xyz", wx.OPEN)
    if dlg.ShowModal() == wx.ID_OK:
         self.xyz_source=str(dlg.GetPath())
         self.fname_txt_ctl.SetValue(self.xyz_source)
         dlg.Destroy()
         return
    if dlg.ShowModal() == wx.ID_CANCEL:
         dlg.Destroy()
         return

If I want to cancel, I have to hit the "Cancel" button twice. If I reverse the order of the conditionals, Cancel works OK, but then I have to hit the "Open" button twice to get a file name. Using "elif" instead of the second "if" doesn't change the behavior. What is the correct way to do this? Thanks.

bob.sacamento
  • 6,283
  • 10
  • 56
  • 115

2 Answers2

3

With newer versions of wxPython (2.8.11+) I would use the context manager, like this:

def open_filedlg(self,event):
    with wx.FileDialog(self, "Choose XYZ file", getcwd(), "",
             "XYZ files (*.dat)|*.dat|(*.xyz)|*.xyz", wx.OPEN) as dlg:
        dlgResult = dlg.ShowModal()
        if dlgResult == wx.ID_OK:
            self.xyz_source=str(dlg.GetPath())
            self.fname_txt_ctl.SetValue(self.xyz_source)
            return
        else:
            return
        #elif dlgResult == wx.ID_CANCEL:
            #return

The 'with' context manager will automagically call dlg.destroy().

Werner
  • 2,086
  • 1
  • 15
  • 14
  • Thanks. Apparently my version is not new enough. The context manager gives and AttributeError. It doesn't like something about "__exit__". – bob.sacamento Jul 01 '15 at 18:08
  • @bob.sacamento what version of wxPython are you using? Can you show the full traceback? – Werner Jul 02 '15 at 09:39
2

The problem is, that you are opening the dialog twice (once with each 'dlg.ShowModal').

Try something like

dialogStatus = dlg.ShowModal()
if dialogStatus == wx.ID_OK:
    ...
Dante
  • 56
  • 4