Home > Back-end >  Tkinter, I want to change the text of a label, after generating it with a loop
Tkinter, I want to change the text of a label, after generating it with a loop

Time:09-11

So I know the problem is in the, "firstLabelList[2]['text'] = "Yay it worked!" line, but I don't know how to fix it.

from tkinter import *

class LabelLoop():

def __init__(self):
    #create the window 
    window =Tk()
    window.title("Tic Tack Toe! Yay Lets do it!")
    window.geometry("350x450")
    #window.columnconfigure((1, 2, 3,), weight=1)
    #window.rowconfigure((1, 2, 3, 4), weight=1)

 

    x=0
    y=0

    firstLabelList= [0]*3

    #ok, so i have a proof of concept, I can create labels using a loop. 
    #The next thing I want to do is prove that I can add logic to the labels, so I want to make a button
    #that changes the third one. 

    for i in range (3):
        firstLabelList[i]=Label(window, text=f"label {i}").grid(row=x, column=y) 
        x =1

    def on_click():
        firstLabelList[2]['text'] = "Yay it worked!"
        


    changeBttn = Button(window, text="change", command=on_click).grid(row=5, column=0)

    #Here is the problem, how do you fix this? 



    window.mainloop()

LabelLoop()

CodePudding user response:

You're problem is that your are doing .grid() directly. First, create the Label if firstLabelList, then access it again and grid it. The .grid() does not return the object, so you will get None as the return result.

So, the code in the loop should change to:

for i in range (3):
        firstLabelList[i]=Label(window, text=f"label {i}")
        firstLabelList[i].grid(row=x, column=y) 
        x =1
  • Related