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
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.
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
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.