wxPython:使用 wx 设置焦点.如果销毁模式对话框,PostEvent 不起作用



在模式对话框被破坏后,我在设置按钮的焦点时遇到问题。

我是否可以调用来销毁模态对话框或阻止它成为模态然后销毁它?

当wx。PostEvent 触发了一个事件,它会在模式对话框中强制销毁,但据我了解,它不会立即被销毁,这意味着当我执行 SetFocus() 时按钮仍然被禁用。

import wx
import wx.lib.newevent
from threading import Thread
import time
processFinishes, EVT_PROCESS_FINISHES = wx.lib.newevent.NewEvent()
class Dummy(Thread):
    def __init__(self, arg):
        super(Dummy, self).__init__()
        self.arg = arg
    def run(self):
        time.sleep(15)
        print "Posting"
        wx.PostEvent(self.arg , processFinishes(result=(None)))

class MyRegion(wx.Frame):
    def __init__(self, parent):
        wx.Frame.__init__(self, parent)
        self.button = wx.Button(self, label="Click me!")
        self.mybutton2 = wx.Button(self, label="I should have focus!!!")
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(self.button, 0, wx.ALL)
        sizer.Add(self.mybutton2, 0, wx.ALL)
        self.SetSizerAndFit(sizer)
        self.Bind(wx.EVT_BUTTON, self.OnButton)
        self.Bind(EVT_PROCESS_FINISHES, self.OnFinish)
        self.progress = None
        self.t = Dummy(self)
    def OnButton(self, event):
        self.progress = wx.ProgressDialog("Processing",
                                          "Please wait while the processing finishes.")
        self.progress.Pulse()
        self.progress.ShowModal()
        self.t.start()
    def OnFinish(self, _event):
        print "destroyed"
        self.progress.Destroy()
        print "now setting foucs"
        self.mybutton2.SetFocus()
if __name__ == "__main__":
    app = wx.App()
    frame = MyRegion(None)
    frame.Show()
    app.MainLoop()

编辑:

当尝试阻止进度对话框为模式时,以下代码给我错误,指示进度对话框不是模式,而它显然是:

    .....
    def OnButton(self, event):
        # wx.ProgressDialog can also be created with
        # style=wx.wx.PD_APP_MODAL which cannot be made non-modal later on
        # i.e. EndModal() does not work
        self.progress = wx.ProgressDialog("Processing",
                                          "Please wait while the processing finishes.")
        self.progress.Pulse()
        self.progress.ShowModal()
        self.t.start()
    def OnFinish(self, _event):
        print "destroyed"
        # By changing this line
        # wx complains indicating that the progress dialog
        # is not modal whereas a ShowModal was used
        self.progress.EndModal(0) # -> produces a "wx._core.PyAssertionError: C++ assertion "IsModal()" failed at ....srcmswdialog.cpp(221) in wxDialog::EndModal(): EndModal() called for non modal dialog"
        print "now setting foucs"
        self.mybutton2.SetFocus()

模式对话框在返回时重新启用所有内容ShowModal()因此只需直接从OnButton()调用OnFinish()即可。

但是请注意,wxProgressDialog根本不是一个模态对话框(如果是的话,这将是毫无用处的,因为您将无法调用Update()!),因此在这种情况下,您应该在完成它时将其销毁(或使用wxPD_AUTO_HIDE样式告诉它在达到最大进度值时自行消失)。

最新更新