tkinter button created in loop command not working

scruffyboy13

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?

RFairey

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.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

spannablestring is not working for programmatically created button

Tkinter, changing a button and its command

Tkinter button highlight feature stops working after command is called

Change colour of tkinter button created in a loop?

Finding button ids created in a loop

Command substitution in for loop not working

Infinite loop for widget button in tkinter

button command option in tkinter

tkinter: changing button attributes for buttons created in loop

Button command not working in DataTemplate

Python tkinter change individual button parameters created in for loop

Tkinter button command argument

Tkinter Button Commands in For Loop

TKinter using an indexing for loop to pass arguments for a button command

Tkinter assign Command to button

Validate command not working in Tkinter

My Tkinter button command only runs through the loop once

Tkinter button with the command if or else

add a command to tkinter button by a string

how to give different command to buttons created in a loop in tkinter?

Python Tkinter treeview.heading command not working right in for loop

Tkinter - Retrieve text from button created in a loop

Tkinter Button does not execute command

How can I add a new Entry field with a Button? The Entry field was created by a loop in Python Tkinter

Creating Tkinter buttons in a loop and setting the command for each button to take in the indices of the loop

Tkinter button not working geometry error

Why is command attribute of button widget not working as expected in Tkinter?

Pass button text to command as arg with tkinter button

How to get a widget value created in a for loop when button is clicked in python tkinter

TOP Ranking

HotTag

Archive