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?

Sean Duffy
  • 199
  • 6
  • Can you elaborate on what you are trying to accomplish? Maybe show your loop and your later call? – A.E. Drew Jun 13 '13 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? – A.E. Drew Jun 13 '13 at 23:55
  • That did the trick, many thanks! This had me stumped for a good couple of hours. – Sean Duffy Jun 14 '13 at 00:14

0 Answers0