wxPython中parent.Bind和widget.Bind的区别是什么

2024-07-05 11:00:35 发布

您现在位置:Python中文网/ 问答频道 /正文

import wx

class MyPanel(wx.Panel):

    def __init__(self, parent):
        super().__init__(parent)
        btn = wx.Button(self, label="Press me")
        btn.Bind(wx.EVT_BUTTON, self.on_button_press)

    def on_button_press(self, event):
        print("You pressed the button")

class MyFrame(wx.Frame):

    def __init__(self):
        super().__init__(parent=None, title="Hello wxPython")
        panel = MyPanel(self)
        self.Show()

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

在上面的代码中,我们使用btn.Bind将wx.Button绑定到wx.EVT_按钮
如果相反,我们使用以下方式: self.Bind(wx.EVT_BUTTON, self.on_button_press, btn)
结果将与上述相同。现在我的问题是self.Bind和btn.Bind之间的区别


Tags: selfinitbindondefbuttonclassparent
1条回答
网友
1楼 · 发布于 2024-07-05 11:00:35

每个小部件都有一个Id。
事件触发时,传递触发小部件的Id,在本例中为按钮。
将事件绑定到函数可以是特定的或通用的,即特定小部件或触发该事件类型的任何小部件。
简而言之,在本例中,self.Bind绑定任何按钮事件,除非您指定了小部件ID。
见:https://docs.wxpython.org/events_overview.html
希望下面的代码有助于解释。
注意:{}说不要在这个事件上停下来,看看是否还有更多的事件要处理

import wx

class MyPanel(wx.Panel):

    def __init__(self, parent):
        super().__init__(parent)
        btn1 = wx.Button(self, label="Press me 1", pos=(10,10))
        btn2 = wx.Button(self, label="Press me 2", pos=(10,50))
        Abtn = wx.Button(self, label="Press me", pos=(10,90))

    # Bind btn1 to a specific callback routine
        btn1.Bind(wx.EVT_BUTTON, self.on_button1_press)
    # Bind btn2 to a specific callback routine specifying its Id
    # Note the order of precedence in the callback routines
        self.Bind(wx.EVT_BUTTON, self.on_button2_press, btn2)
    # or identify the widget via its number
    #    self.Bind(wx.EVT_BUTTON, self.on_button2_press, id=btn2.GetId())
    # Bind any button event to a callback routine
        self.Bind(wx.EVT_BUTTON, self.on_a_button_press)

    # button 1 pressed
    def on_button1_press(self, event):
        print("You pressed button 1")
        event.Skip()

    # button  2 pressed
    def on_button2_press(self, event):
        print("You pressed button 2")
        event.Skip()

    # Any button pressed
    def on_a_button_press(self, event):
        print("You pressed a button")
        event.Skip()

class MyFrame(wx.Frame):

    def __init__(self):
        super().__init__(parent=None, title="Hello wxPython")
        panel = MyPanel(self)
        self.Show()

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

相关问题 更多 >