在wxpython文件对话框中处理多个条件的正确方法是什么?

在wxpython文件对话框中处理多个条件的正确方法是什么?,wxpython,filedialog,Wxpython,Filedialog,我的wxpython GUI具有打开文件对话框的方法: 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(d

我的wxpython GUI具有打开文件对话框的方法:

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

如果我想取消,我必须按两次“取消”按钮。如果我颠倒条件的顺序,Cancel可以正常工作,但是我必须按“Open”按钮两次才能获得文件名。使用“elif”而不是第二个“if”不会改变行为。正确的方法是什么?谢谢。

问题是,您打开对话框两次(每个“dlg.showmodel”打开一次)

试试像这样的东西

dialogStatus = dlg.ShowModal()
if dialogStatus == wx.ID_OK:
    ...

问题是,您打开对话框两次(每个“dlg.showmodel”打开一次)

试试像这样的东西

dialogStatus = dlg.ShowModal()
if dialogStatus == wx.ID_OK:
    ...

对于wxPython(2.8.11+)的较新版本,我将使用上下文管理器,如下所示:

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

“with”上下文管理器将自动调用dlg.destroy()。

对于wxPython(2.8.11+)的较新版本,我将使用上下文管理器,如下所示:

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

“with”上下文管理器将自动调用dlg.destroy()。

然后对多个条件使用if/elif/else。然后对多个条件使用if/elif/else。谢谢。显然我的版本还不够新。上下文管理器提供和AttributeError。它不喜欢关于“退出”的内容。@bob.sacamento您使用的是什么版本的wxPython?你能展示完整的追踪吗?谢谢。显然我的版本还不够新。上下文管理器提供和AttributeError。它不喜欢关于“退出”的内容。@bob.sacamento您使用的是什么版本的wxPython?你能显示完整的回溯吗?