parent.Bind和widget.Bind在wxPython中有什么区别

问题描述 投票:2回答:1
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_BUTTON。如果相反,我们使用这种方式:self.Bind(wx.EVT_BUTTON, self.on_button_press, btn)结果将与上面相同。现在我的问题是self.Bind和btn.Bind之间的区别。

python wxpython wxpython-phoenix
1个回答
3
投票

每个小部件都有一个ID。触发事件时,传递触发窗口小部件的ID(在本例中为按钮)。将事件绑定到函数可以是特定的或通用的,即特定的窗口小部件或触发该事件类型的任何窗口小部件。简而言之,在这种情况下,除非您指定窗口小部件ID,否则self.Bind绑定任何按钮事件。请参阅:https://docs.wxpython.org/events_overview.html希望下面的代码可以帮助解释。N.B. event.Skip()说不要在此事件上停止,请查看是否还有其他事件要处理。

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()
© www.soinside.com 2019 - 2024. All rights reserved.