views:

61

answers:

2

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()
+1  A: 

Call GetId() on your event in the handler and compare the id it returns to the ids of your staticBitmaps. If you need an example let me know and Ill update my answer

volting
I tried this on the code I posted above by passing a counter as the id argument to the staticBitmap constructor (0 to n-1). However, calling GetId() on the event always returns -202, for some reason...
Johnny
Well theres two ways that you could do it create a list of Id's for your images in advance (and use them when instantiating your staticBitmaps) then just compare them... or put your image objects into a list, then to compare there Ids you can call GetId() on them also, again if you want an example Ill add it... it might be easier to follow..
volting
Sorry I just noticed that I kinda miss read your comment. If your getting -202 it means your doing something wrong.. if you are actually using the counter.. then you should be getting them numbers back with GetId() an ID of -202 suggests that your passing a random Id
volting
A: 

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.

Mike Driscoll