获取一个称为事件的按钮的名称的最佳方式? [英] Best way to get the name of a button that called an event?
本文介绍了获取一个称为事件的按钮的名称的最佳方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在以下代码中(由此代码段所启发),我使用一个事件处理程序 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屋!
查看全文