0
from tkinter import *
root=Tk()
frm=Frame(root)
frm.pack()

btn=[0]
r=[0,0,0,0,1,1,1,2,2,2]
c=[0,0,1,2,0,1,2,0,1,2]

def btnclick(count):
    btn[count].config(text="X")

for i in range(1,10):
    btn.append(Button(frm,text=" ",command=btnclick(i)))
    btn[i].grid(row=r[i],column=c[i])
    
root.mainloop()

why i am not able to set button label x on clicking each button it is show following error

Traceback (most recent call last):   File "d:\python\my
programs\xnodemo.py", line 14, in <module>  
    btn.append(Button(frm,text=" ",command=btnclick(i)))     File "d:\python\my programs\xnodemo.py", line 11, in btnclick  
    btn[count].config(text="X")   
IndexError: list index out of range

1 Answers1

1

You need to create a local variable, and pass that as a parameter:

btn.append(Button(frm,text=" ",command=lambda i=i:btnclick(i)))

See the problem here:

for i in range(1,10):
    btn.append(Button(frm,text=" ",command=btnclick(i))

The function is executed as soon as it is called. Now, i is initially 1 because of range(1,10). So 1 is passed as an argument. But, the index 1 doesn't exists because the list was initally empty.

  • yes i have used this before but and it worked can u please explain – Kunal Yadav Aug 09 '21 at 12:31
  • so why does this doesn't happen while using lambda expression – Kunal Yadav Aug 09 '21 at 12:56
  • @KunalYadav lambda returns the function with the given arguments, while simply calling the function, well calls it, I would say that decorators do sth similar so if you look those up you may understand how lambda works (if that is how it works but it is a way I can explain this concept) – Matiiss Aug 09 '21 at 13:06
  • @Matiiss i did not understood how out of index error is not given by using lambda as it is also just calling the function btnclick() – Kunal Yadav Aug 09 '21 at 13:17
  • @KunalYadav because it doesn't call that function right away, otherwise you are trying to access an index before the item has been appended to the list, so obvs you get an index error, also you should start range from 0, otherwise you are not doing anything with the first item in the list, and you will get the same error when clicking the last button – Matiiss Aug 09 '21 at 13:23