Search code examples
pythonpython-3.xwxpython

AddPendingEvent has no effect


I want to send events using AddPendingEvent. However, nothing happens after calling AddPendingEvent. The following is an example, where a button is expected to send a wx.CloseEvent to the frame.

import wx

class MainFrame(wx.Frame):
    def __init__(self):
        super(wx.Frame, self).__init__(None, wx.ID_ANY, 'Test')

        self.button = wx.Button(self, wx.ID_ANY, 'Close', self.GetClientSize()/2)
        self.button.Bind(wx.EVT_BUTTON, self.OnButton)

        self.Bind(wx.EVT_CLOSE, self.OnClose)

        self.Show()

    def OnButton(self, event: wx.CommandEvent):
        self.AddPendingEvent(wx.CloseEvent())

    def OnClose(self, event: wx.CloseEvent):
        self.Destroy()

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

I have also tried QueueEvent or wx.PostEvent, the results are the same.


Solution

  • You should go by PyCommandEvent and create & enqueue an event of type wx.EVT_CLOSE as in:

    self.AddPendingEvent(wx.PyCommandEvent(wx.EVT_CLOSE.typeId, self.GetId()))