Tkinter unexpected behaviour Tkinter unexpected behaviour tkinter tkinter

Tkinter unexpected behaviour


Your closures (lambdas) are not working as you expect them to. They keep references to i which is mutated as the loop iterates, and in the end all lambdas from the same loop refer to the same single last button.

Here's an illustration of the behaviour:

>>> k = []>>> for i in range(5):...     k.append(lambda: i)>>> k[0]()4>>> [f() for f in k][4, 4, 4, 4, 4]


You can fix the problem with:

for i in range(len(buttons)-1):    buttons[i].bind("<Down>", lambda x, i=i: buttons[i+1].focus_set())for i in range(1, len(buttons)):    buttons[i].bind("<Down>", lambda x, i=i: buttons[i-1].focus_set())

Note the i=i argument to the lambda closure.