繁体   English   中英

Tkinter,我想改变一个label的文本,用循环生成它之后

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

所以我知道问题出在“firstLabelList[2]['text'] = “Yay it works”这一行。但我不知道如何解决它。

从 tkinter 进口 *

class 标签循环():

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

标签循环()

你的问题是你正在做.grid()直接。 首先,如果firstLabelList ,则创建 Label ,然后再次访问它并对其进行网格化。 .grid()不返回 object,因此您将得到 None 作为返回结果。

因此,循环中的代码应更改为:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM