【问题标题】:What is the proper way to handle multiple conditionals in a wxpython file dialog?在 wxpython 文件对话框中处理多个条件的正确方法是什么?
【发布时间】:2015-07-01 00:12:48
【问题描述】:

我的 wxpython GUI 有一个打开 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

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

【问题讨论】:

    标签: wxpython filedialog


    【解决方案1】:

    对于较新版本的 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()。

    【讨论】:

    • 谢谢。显然我的版本不够新。上下文管理器给出和 AttributeError。它不喜欢“exit”。
    • @bob.sacamento 您使用的是哪个版本的 wxPython?你能显示完整的回溯吗?
    【解决方案2】:

    问题是,您打开对话框两次(每个 'dlg.ShowModal' 一次)。

    尝试类似的东西

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

    【讨论】:

    • 然后将 if/elif/else 用于多个条件。
    猜你喜欢
    • 2011-11-29
    • 2013-07-24
    • 2020-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多