Tkinter, I want to change the text of a label, after generating it with a loop

Question:

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()

Asked By: Anson.A

||

Answers:

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
Answered By: JayMan146
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.