tkinter gui set text on clicking

Question:

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:pythonmy
programsxnodemo.py", line 14, in <module>  
    btn.append(Button(frm,text=" ",command=btnclick(i)))     File "d:pythonmy programsxnodemo.py", line 11, in btnclick  
    btn[count].config(text="X")   
IndexError: list index out of range
Asked By: Kunal Yadav

||

Answers:

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.

Answered By: user15801675
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.