Skip to content Skip to sidebar Skip to footer

Wxpython: How To Determine Source Of An Event

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 E

Solution 1:

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.

Solution 2:

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

Solution 3:

You can use GetId(), but make sure you keep it unique across your program. I am posting modified code to show how can you do it. Despite of using filenames as 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's to image files
    filenames = []

    for i inrange(num):
        filenames.append("img"+str(i)+".png")
    for imgid,fn inenumerate(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()

defOnDClick(self, event):

    print'you clicked img%s'%(event.GetId() )

You can use dict and map every file name to id, by this way you will keep track of it all through your programe.

Post a Comment for "Wxpython: How To Determine Source Of An Event"