wxPython: binding multiple widgets - Frame e Panel - to the same handler

110 views Asked by At

Let's assume to have this code:

#!/usr/bin/python
# _*_ coding: utf-8 _*_
import wx

class wxappsubclass(wx.App):
  def OnInit(self):
    frame=wxframesubclass(None, -1, 'MyName')
    frame.Show(True)
    return True

class wxframesubclass(wx.Frame):
  def __init__(self, parent, id, title):
    wx.Frame.__init__(self, parent, id, title, wx.DefaultPosition, size=(320, 240))
    panel=panel1(self)
    menubar=wx.MenuBar()
    menufile=wx.Menu()
    ExitItem=menufile.Append(wx.NewId(), '&Exit\tCtrl+Q', "Exit")
    menubar.Append(menufile, '&File')
    self.SetMenuBar(menubar)

    ## BINDING ##
    self.Bind(wx.EVT_MENU, self.CloseProgramFromFrame, ExitItem)

  def CloseProgramFromFrame(self, event):
    self.Close(True)

class panel1(wx.Panel):
  def __init__(self, parent):
    wx.Panel.__init__(self, parent, -1)
    ID_EXIT_BUTTON=wx.NewId()
    ExitButton=wx.Button(self, wx.NewId(), label="Exit")
    self.Bind(wx.EVT_BUTTON, self.CloseProgramFromPanel, ExitButton)

  def CloseProgramFromPanel(self, event):
    parente=self.GetParent()
    parente.Destroy()

if __name__ == '__main__':
  app=wxappsubclass()
  app.MainLoop()

Now, If I want to bind the same event handler ("CloseProgramFromFrame" in this example) from class "panel1()" how to do?

i.e.: I want to delete "CloseProgramFromPanel()" method in the "panel1" then bind "Exit" button - i.e. EVT_BUTTON in the "panel1()" - to the "CloseProgramFromFrame()" method in the "wxframesubclass()", how to do? I'm a bit confused...

1

There are 1 answers

0
Vader On BEST ANSWER

One of the possible ways is:

#!/usr/bin/python
# _*_ coding: utf-8 _*_
import wx

class wxappsubclass(wx.App):
  def OnInit(self):
    frame=wxframesubclass(None, -1, 'MyName')
    frame.Show(True)
    return True

class wxframesubclass(wx.Frame):
  def __init__(self, parent, id, title):
    wx.Frame.__init__(self, parent, id, title, wx.DefaultPosition, size=(320, 240))
    self.panel=panel1(self)
    menubar=wx.MenuBar()
    menufile=wx.Menu()
    ExitItem=menufile.Append(wx.NewId(), '&Exit\tCtrl+Q', "Exit")
    menubar.Append(menufile, '&File')
    self.SetMenuBar(menubar)

    ## BINDING ##
    self.Bind(wx.EVT_MENU, self.CloseProgramFromFrame, ExitItem)
    self.Bind(wx.EVT_BUTTON, self.CloseProgramFromFrame, self.panel.ExitButton)

  def CloseProgramFromFrame(self, event):
    self.Close(True)

class panel1(wx.Panel):
  def __init__(self, parent):
    wx.Panel.__init__(self, parent, -1)
    ID_EXIT_BUTTON=wx.NewId()
    self.ExitButton=wx.Button(self, wx.NewId(), label="Exit")

if __name__ == '__main__':
  app=wxappsubclass()
  app.MainLoop()