wxPython:窗口和事件ID

时间:2010-08-05 02:33:17

标签: python wxpython

我有一个Panel,我在其上显示一个初始化为id为2的StaticBitmap。当我将鼠标事件绑定到图像并在事件上调用GetId()时,它返回-202。为什么呢?

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()

1 个答案:

答案 0 :(得分:0)

您正在打印事件的ID,而不是位图的ID。

尝试print event.GetEventObject().GetId()

GetEventObject返回与该事件相关联的窗口小部件,在本例中为StaticBitmap

FWIW,我从来不需要为任何小部件分配ID,你可能也不需要。

编辑:我看到了你问过的其他一些问题,这就是我的建议,特别是如果GetEventObject正在回归父母(如果那是真的,我会非常惊讶,你应该仔细检查):

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...