在循环命令中创建按钮失败 [英] Creating buttons inside loop command failing

查看:22
本文介绍了在循环命令中创建按钮失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在python中使用Tkinter,尝试制作编号按钮,使用self.do(x)将数字x添加到字符串变量中.这段特定代码在循环中(以节省空间)的问题在于它将最后一个数字添加到字符串中(即,在本例中为 9).这是因为它在此之后调用函数,并使用 num[i] 的最新值.有什么办法可以纠正吗?

Using Tkinter in python, trying to make numbered buttons, which use self.do(x) to add the number x to a string variable. The problem with this particular piece of code being in a loop (to save space), is that it will add the LAST number to the string (ie, 9 in this example). This is because it calls the function after this, and uses the latest value of num[i]. Is there any way to correct this?

self.numButton = []
num = []
for i in range(9):
    num.append(i + 1)
    self.numButton.append(Button(root,text=num[i],command=lambda: self.do(num[i])))

推荐答案

lambda 函数中使用默认值:

Use a default value in your lambda function:

self.numButton.append(
    Button(root,text=num[i],command=lambda i=i: self.do(num[i])))

默认值在 lambda 函数被定义 时被计算并绑定到函数(而不是在运行时).因此,稍后,当按下按钮并调用回调不带任何参数时,将使用默认值.

The default value is evaluated and bound to the function at the time the lambda function is defined (as opposed to when it is run). So, later, when the button is pressed and the callback is called without any arguments, the default value is used.

由于 i 的不同默认值绑定到每个 lambda 函数,i 的适当值用于每个回调.

Since a different default value for i is bound to each lambda function, the appropriate value for i is used for each callback.

如果回调需要额外的参数,例如在event上,只需将具有默认值的参数放在最后.例如,

If the callback requires additional arguments, such as on event, just place the parameter with default value at the end. For example,

root.bind('Key-{n}'.format(n=num[i]), lambda e, i=i: self.do(num[i]))

这篇关于在循环命令中创建按钮失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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