wxPython:如何确定事件的来源 [英] wxPython: how to determine source of an event

查看:32
本文介绍了wxPython:如何确定事件的来源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个面板,上面有多个图像,每个图像都绑定到同一个事件处理程序.如何确定从事件处理程序中单击了哪个图像?我尝试使用 Event.GetEventObject() 但它返回父面板而不是单击的图像.

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.

这是一些示例代码:

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

推荐答案

在循环中,为每个 StaticBitmap 小部件指定一个唯一名称.一种方法是这样的:

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

这一直对我有用.

这篇关于wxPython:如何确定事件的来源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆