0

I want to take this code:

buttons[0]=Button(boardFrame,text=' ', command=lambda: boardButtonClick(1))
buttons[0].grid(row=0,column=0,sticky='news',ipadx=10,ipady=10)

buttons[1]=Button(boardFrame,text=' ', command=lambda: boardButtonClick(2))
buttons[1].grid(row=0,column=1,sticky='news',ipadx=10,ipady=10)

buttons[2]=Button(boardFrame,text=' ', command=lambda: boardButtonClick(3))
buttons[2].grid(row=0,column=2,sticky='news',ipadx=10,ipady=10)

buttons[3]=Button(boardFrame,text=' ', command=lambda: boardButtonClick(4))
buttons[3].grid(row=1,column=0,sticky='news',ipadx=10,ipady=10)
....

and so on...

And to make it short using a for loop. that's what I tried:

i=0
for j in range(0,3):
    for k in range(0,3):
        buttons[i]=Button(boardFrame,text=' ', command=lambda: boardButtonClick(i))
        buttons[i].grid(row=j,column=k,sticky='news',ipadx=10,ipady=10)
        i+=1

All the arguments works good, But there is a problem with the argument that sent to the function in this part: command=lambda: boardButtonClick(i)

Thanks.

Matan
  • 146
  • 13
  • And what is the problem with that? Are you getting an error? You have unexpected value? what value you get? – Gargantua Oct 17 '19 at 07:48
  • command=lambda: boardButtonClick(i+1) – Wertartem Oct 17 '19 at 07:56
  • 1
    There is one more step to be done: `command=lambda i=i+1: boardButtonClick(i)`. Read [Tkinter assign button command in loop with lambda](https://stackoverflow.com/questions/17677649/tkinter-assign-button-command-in-loop-with-lambda). – Henry Yik Oct 17 '19 at 08:55
  • @HenryYik that's was my problem! thank you. You can post it as answer. – Matan Oct 17 '19 at 08:59
  • No problem. You can upvote the answer linked in the question instead. – Henry Yik Oct 17 '19 at 09:02

1 Answers1

1

According to your first code part, you are starting with

buttons[0]=Button(boardFrame,text=' ', command=lambda: boardButtonClick(1))

But in your loop, your are starting with i=0 and then :

buttons[i]=Button(boardFrame,text=' ', command=lambda: boardButtonClick(i))

This line will be the following :

buttons[0]=Button(boardFrame,text=' ', command=lambda: boardButtonClick(0))

If you want your first code part result, try this instead:

buttons[i]=Button(boardFrame,text=' ', command=lambda: boardButtonClick(i+1))
Arkenys
  • 343
  • 1
  • 11
  • I forgot to say that I care the `i=0` and `i=1` issue in the `boardButtonClick()` function itself so this is not the problem. The problem was that `boardButtonClick(i)` didn't send `i` to the function at all. @HenryYik solved it with adding `command=lambda i=i+1: boardButtonClick(i)` – Matan Oct 17 '19 at 09:02