问题描述
我想生成 n
数量的 Tkinter Button
来做不同的事情.我有这个代码:
I want to generate n
amount of Tkinter Button
s which do different things. I have this code:
import Tkinter as tk
for i in range(boardWidth):
newButton = tk.Button(root, text=str(i+1),
command=lambda: Board.playColumn(i+1, Board.getCurrentPlayer()))
Board.boardButtons.append(newButton)
如果 boardWidth
是 5,虽然我得到了标记为 1
到 5
的按钮,但当点击它们时,它们都会执行 Board.playColumn(5、Board.getCurrentPlayer())
.
If boardWidth
is 5, though I get buttons labelled 1
to 5
, when clicked they all do Board.playColumn(5, Board.getCurrentPlayer())
.
我需要第一个按钮做Board.playColumn(1, Board.getCurrentPlayer())
,第二个按钮做Board.playColumn(2, Board.getCurrentPlayer())
等等.
I need the first button to do Board.playColumn(1, Board.getCurrentPlayer())
, the second to do Board.playColumn(2, Board.getCurrentPlayer())
and so on.
推荐答案
我认为问题在于 lambda
在 i
之后拾取了最终值code>for 循环结束.这应该可以解决这个问题(未经测试):
I think the problem is that the lambda
is picking up the final value of i
after the for
loop ends. This should fix that (untested):
import Tkinter as tk
for i in range(boardWidth):
newButton = tk.Button(root, text=str(i+1),
command=lambda j=i+1: Board.playColumn(j, Board.getCurrentPlayer()))
Board.boardButtons.append(newButton)
更新
顺便说一句,这是通过向 lambda
函数添加一个参数来实现的,默认值是根据 i
在循环中创建每个函数时的值计算得出的与 i
中的表达式稍后执行时通过闭包返回的最终值相比.
BTW, this worked by adding an argument to the lambda
function with a default value calculated from the value of i
at the time each one is created in the loop rather than referring back to the final value of i
through a closure when the expression within it executes later.
这篇关于动态生成 Tkinter 按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!