views:

47

answers:

1

I have a Panel on which I display a StaticBitmap initialised with an id of 2. When I bind a mouse event to the image and call GetId() on the event, it returns -202. Why?

import wx

class MyFrame(wx.Frame):

    def __init__(self, parent, id=-1):

        wx.Frame.__init__(self,parent,id)

        self.panel = wx.Panel(self,wx.ID_ANY)

        img = wx.Image("img1.png",wx.BITMAP_TYPE_ANY)
        img2 = wx.StaticBitmap(self.panel,2,wx.BitmapFromImage(img))
        print img2.GetId() # prints 2

        img2.Bind(wx.EVT_LEFT_DOWN,self.OnDClick)

    def OnDClick(self, event):

        print event.GetId() # prints -202

if __name__ == "__main__":

    app = wx.PySimpleApp()
    frame = MyFrame(None)
    frame.Show()
    app.MainLoop()
A: 

You're printing the event's ID, not the bitmap's ID.

Try print event.GetEventObject().GetId()

GetEventObject returns the widget associated with the event, in this case, the StaticBitmap.

FWIW, I've never needed to assign ID's to any widgets, and you probably shouldn't need to either.

Edit: I saw some other questions you asked and this is what I would recommend, especially if GetEventObject is returning the parent instead (I'm very surprised if that's true, you should double check):

import functools

widget1.Bind(wx.EVT_LEFT_DOWN, functools.partial(self.on_left_down, widget=widget1))
widget2.Bind(wx.EVT_LEFT_DOWN, functools.partial(self.on_left_down, widget=widget2))
# or the above could be in a loop, creating lots of widgets

def on_left_down(self, event, widget):
    # widget is the one that was clicked
    # event is still the wx event
    # handle the event here...
FogleBird
Both event.GetId() and event.GetEventObject().GetId() will return the bitmaps Id http://www.wxpython.org/docs/api/wx.Event-class.html#GetId
volting
@volting: That's not how I interpret the documentation you linked to.
FogleBird
Yes I may have misinterpreted the linked doc, I cant seem to find anything that better supports my statement, but personal experience tells me they (event.GetId() and event.GetEventObject().GetId()) produce the same result, try it out for yourself
volting
I tried both the event's GetId() and event.GetEventObject()'s GetId() and they are both producing -202 in the handler. There must be some simple thing I am doing wrong... Thanks for both of your input
Johnny
Aaahhh but this functools hack works. Nice.
Johnny
Fogle - you don't use the standard wx.IDs?
Steven Sproat
@Steven Sproat: I do use wx.ID_OK, wx.ID_CANCEL, etc. when applicable. Forgot to mention that.
FogleBird
@Steven Sproat: FYI - I just answered one of your old questions.
FogleBird