问题描述
def __init__(self,parent):
self.tickets = []
for i in list(range(15)):
self.intRandomNum=self.getRandomNum(i)
self.tickets.append(wx.StaticBitmap(self.panels2[i],-1,wx.Bitmap(self.ticketimages[self.intRandomNum])))
self.tickets[i].Bind(wx.EVT_LEFT_DOWN,self.cardChoice)
def cardChoice(self,event):
alert = wx.MessageDialog(self,_("Do you want to choice this card?"),_("Cardchoice"),wx.YES_NO|wx.ICON_EXCLAMATION)
if alert.ShowModal() == wx.ID_YES:
ret = wx.MessageDialog(self,_("This card:"+repr(self.intRandomNum)),wx.YES_NO|wx.ICON_EXCLAMATION)
ret.ShowModal()
通过 intRandomNum 的输出,我只能得到最后一个随机值。但是如何输出我点击的卡片?使用 Bind,我不认为我可以传递额外的参数:
解决方法
可以在 lambda
命令中使用 event
函数为 Bind
传递其他参数。
以这种方式使用,它允许您在 append
之后使用 event
参数。
请注意,callback
函数必须允许附加参数。
这里的事件 callback
函数为可能的参数提供默认值,以防它们不被发送(例如,flag3
)。
import wx
class TestFrame(wx.Frame):
def __init__(self,*args):
wx.Frame.__init__(self,*args)
panel = wx.Panel(self,-1)
button = wx.Button(panel,-1,"Click me",pos=(10,10),size=(100,40))
button.Bind(wx.EVT_BUTTON,lambda event: self.OnButton(event,flag1="1",flag2="2"))
self.Show()
def OnButton(self,event,flag1=None,flag2=None,flag3=None):
print ("The Button was pressed")
print ("Flag1 was set to ",flag1)
print ("Flag2 was set to ",flag2)
print ("Flag3 was set to ",flag3)
if __name__ == "__main__":
app = wx.App()
myframe = TestFrame(None,"Button lambda event Test")
app.MainLoop()
编辑
以上适用于文字赋值,但在循环中使用变量,循环计数的值不断变化并保留为最终值。
问题是,据我所知,lambda 函数在执行时评估表达式,因此它获取变量的最终/当前值。
在这里,我调整了 lambda
的构造以允许这一点,即时值为“y”。
import wx
class TestFrame(wx.Frame):
def __init__(self,-1)
sizer = wx.BoxSizer(wx.VERTICAL)
buttons = []
for i in range(10):
buttons.append(wx.Button(panel,id = i,label=str(i),40)))
sizer.Add(buttons[i])
lmda = lambda event,y = i: self.OnButton(event,flag1=int(y),flag2="z")
buttons[i].Bind(wx.EVT_BUTTON,lmda )
panel.SetSizer(sizer)
self.Show()
def OnButton(self,flag3=None):
print ("The Button was pressed",flag1)
if __name__ == "__main__":
app = wx.App()
myframe = TestFrame(None,"Button lambda event Test")
app.MainLoop()
请注意,lambda
是单独创建的,纯粹是为了方便和清晰。