Generate Tkinter Buttons dynamically

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)

Update

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.

Leave a Comment