3

I'm creating an application in Python using Tkinter where there will be a grid of buttons, and I'm creating the buttons using nested for loops. When clicked, each button has a callback function which also passes two arguments containing the coordinates of itself. I tried to set this up by assigning each button with its own callback lambda like so:

self.board[row][col].config(command=lambda: switch(row, col))

However this doesn't work because rather than the callback for each function contaning its coordinates, e.g.

command=lambda: switch(2, 4)

it just contains the variables row and col, which means the values end up being 4 for every button since the loops end at 4.

So to summarise, I'm looking for a way to hard-code arguments into a function call. Obviously I can solve this by not using loops and just defining every single button explicitly, but is there any other way to do this?

3
  • Can you elaborate on what you are trying to accomplish? Maybe show your loop and your later call? Commented Jun 13, 2013 at 23:38
  • I think I sussed it out. Why don't you store the row and col within whatever the object is at board[row][col] and then have the command use that object's members? Commented Jun 13, 2013 at 23:55
  • That did the trick, many thanks! This had me stumped for a good couple of hours. Commented Jun 14, 2013 at 0:14

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.