Your anonymous lambda
functions are can be though of as closures (as @abernert points out, they're not actually closures in Python's case) - they "close over" the variable i
, to reference it later. However, they don't look up the value at the time of definition, but rather at the time of calling, which is some time after the entire while
loop is over (at which point, i
is equal to 10).
To fix this, you need to re-bind the value of i
to a something else for the lambda to use. You can do this in many ways - here's one:
...
i = 1
while i < 10:
# Give a parameter to the lambda, defaulting to i (function default
# arguments are bound at time of declaration)
newButton = Button(F, text="Show Number",
command=lambda num=i: showNumber(num))
...
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…