Skip to content
Advertisement

Rename the label in tkinter

I work with tkinter. I want to change the name of the labels. By entering the characters in the field and hitting the button, the labels are renamed one by one. That is, the first time I enter the character “Hello”, then that character is inserted in the label; It is then removed from the field. This time I have to enter a character for the next label. And so on until the end (With the help of the for loop). I did this but it only works for the first label and does not go to the next label):

win=Tk()
size=3
lbls=[]
frms=[]
def func():
    for i in range(6,9):
        lbls[i].configure(text=name.get())
        
for i in range(size):
    for j in range(size):
        frm=Frame(win,bd=2,relief="sunken")
        frm.grid(row=i,column=j)
        frms.append(frm)
        lbl=Label(frm,bg="white",fg="red",width="5")
        lbl.grid(row=0,column=0)
        lbls.append(lbl)
name=Entry(win)
name.grid(row=4,column=0)
btn=Button(win,text="Start",font=("Arial",14),command=func)
btn.grid(row=3,column=0)
win.mainloop()

Advertisement

Answer

You need to use a counter and increase it inside the function. Basically, for loop wont wait for you to type in something and press the button:

counter = 0
def func():
    global counter

    lbls[counter].configure(text=name.get()) 
    
    counter += 1 # Increase it by 1
    if counter >= len(lbls): # If counter is greater than items in list, then reset
        counter = 0
    name.delete(0,'end') # Clear the entry

This will keep updating the text each time you press the button.


Some designing tip: Add columnspan for your button and entry

name.grid(row=4,column=0,columnspan=3)
btn.grid(row=3,column=0,columnspan=3)
Advertisement