0

I'm trying to recreate minesweeper in python using tkinter and i'm creating my grid using a 2d list. i have to use lambda: to run my command because it's taking arguments but when i click a button what is happening is it is printing the position of the last button e.g. if the grid is 9x9 it will print 8 8.

def play():
    global game
    game = tk.Toplevel(root)
    game.title("Minesweeper")
    grid = [[tk.Button(game, text = "", command = lambda: show(i, j), width = 4, height = 2) for j in range(cols)] for i in range(rows)]
    [[grid[i][j].grid(row = i, column = j) for j in range(cols)] for i in range(rows)]

def show(i, j):
    print(i, j)

Does anyone know how i can fix this?

1 Answers1

3

Change the lambda to: lambda i=i, j=j: show(i, j)

This will capture the values of i and j at the time the lambda is created. What's happening instead is it is looking up i and j in the scope of the lambda, but at the time the button is clicked, by which time the loop in the list comprehension is complete and i and j are both 8.

RFairey
  • 736
  • 3
  • 9