Cather Steincamp
Cather Steincamp

Reputation: 104

Is there a way to get the button or menu item object from the event in wxPython?

What I would like to do is bind a single function to multiple buttons or menu items, and have the function make decisions based on which menu item is chosen. For example:

import wx

class TinkerFrame( wx.Frame ):
    
    def __init__(self):
    
        super().__init__(parent=None, title='Sandbox')
        
        self.panel = wx.Panel(self)
        self.sizer = wx.BoxSizer(wx.HORIZONTAL)  
        
        self.buttons  = {}
        
        self.buttons['one'] = wx.Button(self.panel, label='Button 1')
        self.buttons['one'].Bind( wx.EVT_BUTTON, self.buttonPressed)
        
        self.buttons['two'] = wx.Button(self.panel, label='Button 2')
        self.buttons['two'].Bind( wx.EVT_BUTTON, self.buttonPressed) 
        
        self.buttons['three'] = wx.Button(self.panel, label='Button 3' )
        self.buttons['three'].Bind( wx.EVT_BUTTON, self.buttonPressed)

        for thisbutton in self.buttons:
            self.sizer.Add( self.buttons[thisbutton], 0, wx.ALL | wx.CENTER, 5 )
            
        self.panel.SetSizer(self.sizer)
        self.Show()
        
    def buttonPressed(self, event):
        
        thebuttonpressed = False # <---- THIS IS WHAT I'M LOOKING FOR
        
        if thebuttonpressed == self.buttons['one']:
            print( 'You pressed button 1' )
        elif thebuttonpressed == self.buttons['two']:
            print( 'You pressed button 2' )
        elif thebuttonpressed == self.buttons['three']:
            print( 'You pressed button 3' )
        else:
            print( 'I cannot figure out which button you pressed.' )


        
        
        
if __name__ == '__main__':
    app = wx.App()
    frame = TinkerFrame()
    app.MainLoop()

is there a way to do this? I can't seem to extract any information from the event itself, but I clearly don't know what I'm doing, so I'm hoping it's in there somewhere.

UPDATE: changing the line to:

        thebuttonpressed = event.getEventObect()

results in:

AttributeError: 'CommandEvent' object has no attribute 'getEventObject'

SOLUTION

        thebuttonpressed = event.GetEventObject()

It also helps if you include the j...

Upvotes: 0

Views: 343

Answers (1)

Asaf Amnony
Asaf Amnony

Reputation: 205

You can use wx.Event.GetEventObject(), notice the capital G in the method name.

Upvotes: 1

Related Questions