Python的Tkinter的创造按钮循环传递命令参数 [英] Python tkinter creating buttons in for loop passing command arguments

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

问题描述

我想内创造的Tkinter按钮循环。而且每次循环传递我的计数值出作为指令值的参数。因此,当函数是从指令值叫我可以告诉哪个按钮是pssed $ P $和采取相应的行动。问题是,让说,len为3,它将通过游戏3创建标题游戏1的3个按键,但是当任何一个按钮是pressed打印的值总是2,上一次迭代。所以会出现的按钮被制成单独的实体,但在该命令参数的I值似乎是完全一样的。这里是code:

I am trying to create buttons in tkinter within a for loop. And with each loop pass the i count value out as an argument in the command value. So when the function is called from the command value I can tell which button was pressed and act accordingly. The problem is, lets say len is 3, it will create 3 buttons with titles "Game 1" through "Game 3" but when any of the buttons are pressed the printed value is always 2, the last iteration. So it appears the buttons are being made as separate entities, but the i value in the command arguments seem to be all the same. Here is the code:

def createGameURLs(self):
    self.button = []
    for i in range(3):
        self.button.append(Button(self, text='Game '+str(i+1),command=lambda:self.open_this(i)))
        self.button[i].grid(column=4, row=i+1, sticky=W)
def open_this(self, myNum):
    print(myNum)

有没有办法让电流i值,在每次迭代中,坚持使用特定的按钮?谢谢你在前进。

Is there a way to get the current i value, upon each iteration, to stick with that particular button? Thank you in advance.

推荐答案

您的lambda更改为拉姆达I = I:self.open_this(我)

Change your lambda to lambda i=i: self.open_this(i).

这可能看起来不可思议,但这里发生了什么。当您使用lambda来定义功能,open_this调用不会得到变量i你定义函数时的值。相反,它使一个封闭,这是有点像一张纸条给自己说:我应该寻找变量i的值是什么的那个我叫的时间。当然,函数被调用后,循环结束,所以当时我将永远等于从循环中的最后一个值。

This may look magical, but here's what's happening. When you use that lambda to define your function, the open_this call doesn't get the value of the variable i at the time you define the function. Instead, it makes a closure, which is sort of like a note to itself saying "I should look for what the value of the variable i is at the time that I am called". Of course, the function is called after the loop is over, so at that time i will always be equal to the last value from the loop.

使用 I = I 招使你的函数来存储我的当前值在你的lambda定义的时候,而不是等待查找我的价值更高版本。

Using the i=i trick causes your function to store the current value of i at the time your lambda is defined, instead of waiting to look up the value of i later.

这篇关于Python的Tkinter的创造按钮循环传递命令参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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