Tkinter: Addressing Label widget created by for loop

前端 未结 1 1338

The following is my script. Basically, it will ask the user to input a number into the Entry box. Once the user enter a number and click OK, it will give you combination of

相关标签:
1条回答
  • 2020-12-02 01:33

    Sure! Just make a list of labels, call place on each one, and then you can reference them later and change their values. Like so:

    from Tkinter import *
    
    root=Tk()
    
    sizex = 600
    sizey = 400
    posx  = 0
    posy  = 0
    root.wm_geometry("%dx%d+%d+%d" % (sizex, sizey, posx, posy))
    
    labels = []
    
    def myClick():
        del labels[:] # remove any previous labels from if the callback was called before
        myframe=Frame(root,width=400,height=300,bd=2,relief=GROOVE)
        myframe.place(x=10,y=10)
        x=myvalue.get()
        value=int(x)
        for i in range(value):
            labels.append(Label(myframe,text=" mytext "+str(i)))
            labels[i].place(x=10,y=10+(30*i))
            Button(myframe,text="Accept").place(x=70,y=10+(30*i))
    
    def myClick2():
        if len(labels) > 0:
            labels[0].config(text="Click2!")
        if len(labels) > 1:
            labels[1].config(text="Click2!!")
    
    mybutton=Button(root,text="OK",command=myClick)
    mybutton.place(x=420,y=10)
    
    mybutton2=Button(root,text="Change",command=myClick2)
    mybutton2.place(x=420,y=80)
    
    myvalue=Entry(root)
    myvalue.place(x=450,y=10)
    
    root.mainloop()
    

    Also note! In the assignment Mylabel=Label(myframe,text=" mytext "+str(i)).place(x=10,y=10+(30*i)) in the original code, that call sets Mylabel to None, since the place method returns None. You want to separate the place call into its own line, like in the code above.

    0 讨论(0)
提交回复
热议问题