Skip to content Skip to sidebar Skip to footer

How To Override The "Cancel" Button Event Of A ProgressDialog?

The ProgressDialog class allows passing the option wx.PD_CAN_ABORT which adds a 'Cancel' button to the dialog. I need to rebind the event bound to this button, to make it Destroy()

Solution 1:

The Cancel button is not exposed directly in this widget. You can get to it using the dialog's GetChildren method. Here's one way to do it:

import wx

class TestPanel(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent, -1)

        b = wx.Button(self, -1, "Create and Show a ProgressDialog", (50,50))
        self.Bind(wx.EVT_BUTTON, self.OnButton, b)


    def OnButton(self, evt):
        max = 80

        dlg = wx.ProgressDialog("Progress dialog example",
                               "An informative message",
                               maximum = max,
                               parent=self,
                               style = wx.PD_CAN_ABORT
                                | wx.PD_APP_MODAL
                                | wx.PD_ELAPSED_TIME
                                #| wx.PD_ESTIMATED_TIME
                                | wx.PD_REMAINING_TIME
                                )
        for child in dlg.GetChildren():
            if isinstance(child, wx.Button):
                cancel_function = lambda evt, parent=dlg: self.onClose(evt, parent)
                child.Bind(wx.EVT_BUTTON, cancel_function)

        keepGoing = True
        count = 0

        while keepGoing and count < max:
            count += 1
            wx.MilliSleep(250)  # simulate some time-consuming thing...

            if count >= max / 2:
                (keepGoing, skip) = dlg.Update(count, "Half-time!")
            else:
                (keepGoing, skip) = dlg.Update(count)


        dlg.Destroy()

    #----------------------------------------------------------------------
    def onClose(self, event, dialog):
        """"""
        print "Closing dialog!"


########################################################################
class MyFrame(wx.Frame):
    """"""

    #----------------------------------------------------------------------
    def __init__(self):
        """Constructor"""
        wx.Frame.__init__(self, None, title='Progress')
        panel = TestPanel(self)
        self.Show()

if __name__ == '__main__':
    app = wx.App(False)
    frame = MyFrame()
    app.MainLoop()

This is based on the wxPython demo example of this particular dialog. Depending on your platform, you will get the native widget if it exists, otherwise you'll get wx.GenericProgressDialog. I suspect the native widget won't allow you to access the Cancel button at all, but I'm not sure.


Post a Comment for "How To Override The "Cancel" Button Event Of A ProgressDialog?"