I have a Panel with several images on it, each of which is bound to the same event handler. How can I determine which image is being clicked from the event handler? I tried using Event.GetEventObject() but it returns the parent panel instead of the image that was clicked.
Here's some 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()
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()
That's always worked for me.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With