获取调用事件的按钮名称的最佳方法? [英] Best way to get the name of a button that called an event?

查看:24
本文介绍了获取调用事件的按钮名称的最佳方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以下代码中(受 this 片段的启发),我使用了一个事件处理程序 buttonClick 以更改窗口的标题.目前,我需要评估事件的 Id 是否对应于按钮的 Id.如果我决定添加 50 个按钮而不是 2 个,这种方法可能会变得很麻烦.有没有更好的方法来做到这一点?

In the following code (inspired by this snippet), I use a single event handler buttonClick to change the title of the window. Currently, I need to evaluate if the Id of the event corresponds to the Id of the button. If I decide to add 50 buttons instead of 2, this method could become cumbersome. Is there a better way to do this?

import wx

class MyFrame(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, wx.ID_ANY, 'wxBitmapButton',
            pos=(300, 150), size=(300, 350))
        self.panel1 = wx.Panel(self, -1)

        self.button1 = wx.Button(self.panel1, id=-1,
            pos=(10, 20), size = (20,20))
        self.button1.Bind(wx.EVT_BUTTON, self.buttonClick)

        self.button2 = wx.Button(self.panel1, id=-1,
            pos=(40, 20), size = (20,20))
        self.button2.Bind(wx.EVT_BUTTON, self.buttonClick)

        self.Show(True)

    def buttonClick(self,event):
        if event.Id == self.button1.Id:
            self.SetTitle("Button 1 clicked")
        elif event.Id == self.button2.Id:
            self.SetTitle("Button 2 clicked")            

application = wx.PySimpleApp()
window = MyFrame()
application.MainLoop()

推荐答案

你可以给按钮一个名字,然后在事件处理程序中查看这个名字.

You could give the button a name, and then look at the name in the event handler.

当你制作按钮时

b = wx.Button(self, 10, "Default Button", (20, 20))
b.myname = "default button"
self.Bind(wx.EVT_BUTTON, self.OnClick, b)

当按钮被点击时:

def OnClick(self, event):
    name = event.GetEventObject().myname

这篇关于获取调用事件的按钮名称的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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