wxPython,如何触发事件?

2 投票
2 回答
6339 浏览
提问于 2025-04-15 12:54

我正在制作自己的按钮类,这个类是一个面板的子类,我在上面用DC(设备上下文)进行绘图。当我的自定义按钮被按下时,我需要触发wx.EVT_BUTTON事件。我该怎么做呢?

2 个回答

6

创建一个 wx.CommandEvent 对象,使用它的设置方法来设置合适的属性,然后把这个对象传递给 wx.PostEvent。

http://docs.wxwidgets.org/stable/wx_wxcommandevent.html#wxcommandeventctor

http://docs.wxwidgets.org/stable/wx_miscellany.html#wxpostevent

这是一条重复的问题,这里有更多关于如何构建这些对象的信息:

wxPython: 手动调用事件

9

这个维基百科页面对于参考资料来说非常不错。Andrea Gavana 提供了一个相当完整的教程,教你如何制作自己的 自定义控件。以下内容直接来自于那里,并且扩展了 FogleBird 的回答(注意这里的 self 是指 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()

撰写回答