WxPython: how to determine the source of an event

I have a panel with several images on it, each of which is tied to the same event handler. How to determine which image is being called from an event handler? I tried using Event.GetEventObject (), but it returns the parent panel instead of the image that was clicked.

Here is a sample code:

import math import wx class MyFrame(wx.Frame): def __init__(self, parent, id=-1,title="",pos=wx.DefaultPosition, size=wx.DefaultSize, style=wx.DEFAULT_FRAME_STYLE, name="frame"): wx.Frame.__init__(self,parent,id,title,pos,size,style,name) self.panel = wx.ScrolledWindow(self,wx.ID_ANY) self.panel.SetScrollbars(1,1,1,1) num = 4 cols = 3 rows = int(math.ceil(num / 3.0)) sizer = wx.GridSizer(rows=rows,cols=cols) filenames = [] for i in range(num): filenames.append("img"+str(i)+".png") for fn in filenames: img = wx.Image(fn,wx.BITMAP_TYPE_ANY) img2 = wx.BitmapFromImage(img) img3 = wx.StaticBitmap(self.panel,wx.ID_ANY,img2) sizer.Add(img3) img3.Bind(wx.EVT_LEFT_DCLICK,self.OnDClick) self.panel.SetSizer(sizer) self.Fit() def OnDClick(self, event): print event.GetEventObject() if __name__ == "__main__": app = wx.PySimpleApp() frame = MyFrame(None) frame.Show() app.MainLoop() 
+6
python wxpython
source share
3 answers

In your loop, give each StaticBitmap widget a unique name. One way to do this would be something like this:

 wx.StaticBitmap(self, wx.ID_ANY, wx.BitmapFromImage(img), name="bitmap%s" % counter) 

And then increment the counter at the end. Then in the event handler do something like this:

 widget = event.GetEventObject() print widget.GetName() 

It always worked for me.

+4
source share

Call GetId() on your event in the handler and compare the identifier that it returns to the identifiers of your staticBitmaps. If you need an example let me know and I updated my answer

+1
source share

You can use GetId (), but make sure you save it in your program. I am posting modified code to show how you can do this. Despite using the file names in the list.

 def __init__(self, parent, id=-1,title="",pos=wx.DefaultPosition, size=wx.DefaultSize, style=wx.DEFAULT_FRAME_STYLE, name="frame"): wx.Frame.__init__(self,parent,id,title,pos,size,style,name) self.panel = wx.ScrolledWindow(self,wx.ID_ANY) self.panel.SetScrollbars(1,1,1,1) num = 4 cols = 3 rows = int(math.ceil(num / 3.0)) sizer = wx.GridSizer(rows=rows,cols=cols) #you should use dict and map all id to image files filenames = [] for i in range(num): filenames.append("img"+str(i)+".png") for imgid,fn in enumerate(filenames): img = wx.Image(fn,wx.BITMAP_TYPE_ANY) img2 = wx.BitmapFromImage(img) #pass the imgid here img3 = wx.StaticBitmap(self.panel,imgid,img2) sizer.Add(img3) img3.Bind(wx.EVT_LEFT_DCLICK,self.OnDClick) self.panel.SetSizer(sizer) self.Fit() def OnDClick(self, event): print 'you clicked img%s'%(event.GetId() ) 

You can use dict and match each file name with id, so you will track all this through your program.

0
source share

All Articles