I am making my own button class, subclass of a panel where I draw with a DC, and I need to fire wx.EVT_BUTTON when my custom button is pressed. How do I do it?
Asked
Active
Viewed 6,283 times
2 Answers
9
The Wiki is pretty nice for reference. Andrea Gavana has a pretty complete recipe for building your own custom controls. The following is taken directly from there and extends what FogleBird answered with (note self is referring to a subclass of wx.PyControl):
def SendCheckBoxEvent(self):
""" Actually sends the wx.wxEVT_COMMAND_CHECKBOX_CLICKED event. """
# This part of the code may be reduced to a 3-liner code
# but it is kept for better understanding the event handling.
# If you can, however, avoid code duplication; in this case,
# I could have done:
#
# self._checked = not self.IsChecked()
# checkEvent = wx.CommandEvent(wx.wxEVT_COMMAND_CHECKBOX_CLICKED,
# self.GetId())
# checkEvent.SetInt(int(self._checked))
if self.IsChecked():
# We were checked, so we should become unchecked
self._checked = False
# Fire a wx.CommandEvent: this generates a
# wx.wxEVT_COMMAND_CHECKBOX_CLICKED event that can be caught by the
# developer by doing something like:
# MyCheckBox.Bind(wx.EVT_CHECKBOX, self.OnCheckBox)
checkEvent = wx.CommandEvent(wx.wxEVT_COMMAND_CHECKBOX_CLICKED,
self.GetId())
# Set the integer event value to 0 (we are switching to unchecked state)
checkEvent.SetInt(0)
else:
# We were unchecked, so we should become checked
self._checked = True
checkEvent = wx.CommandEvent(wx.wxEVT_COMMAND_CHECKBOX_CLICKED,
self.GetId())
# Set the integer event value to 1 (we are switching to checked state)
checkEvent.SetInt(1)
# Set the originating object for the event (ourselves)
checkEvent.SetEventObject(self)
# Watch for a possible listener of this event that will catch it and
# eventually process it
self.GetEventHandler().ProcessEvent(checkEvent)
# Refresh ourselves: the bitmap has changed
self.Refresh()

Community
- 1
- 1

DrBloodmoney
- 2,786
- 2
- 18
- 17
6
Create a wx.CommandEvent object, call its setters to set the appropriate attributes, and pass it to wx.PostEvent.
http://docs.wxwidgets.org/stable/wx_wxcommandevent.html#wxcommandeventctor
http://docs.wxwidgets.org/stable/wx_miscellany.html#wxpostevent
This is a duplicate, there is more information here on constructing these objects:
-
Could you give me a more detailed explanation? I am not more than a newbie actually. Also, thanks for the answer. – Jul 14 '09 at 21:51
-
@TerabyteST this is what worked for me: `o = self.FindWindowByName(name)`; `e = wx.CommandEvent(wx.EVT_BUTTON.typeId, o.GetId())`; `e.SetEventObject(o)`; `o.ProcessWindowEvent(e)` – ivan866 Nov 28 '22 at 18:23