首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Tkinter:由for循环创建的Addressing Label小部件

Tkinter:由for循环创建的Addressing Label小部件
EN

Stack Overflow用户
提问于 2013-04-04 09:44:30
回答 1查看 16.7K关注 0票数 4

以下是我的脚本。基本上,它会要求用户在输入框中输入一个数字。一旦用户输入一个数字并单击OK,它将根据用户在输入框中键入的数字给出Labels+Buttons组合。

代码语言:javascript
复制
from Tkinter import *

root=Tk()

sizex = 600
sizey = 400
posx  = 0
posy  = 0
root.wm_geometry("%dx%d+%d+%d" % (sizex, sizey, posx, posy))

def myClick():
    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):
        Mylabel=Label(myframe,text=" mytext "+str(i)).place(x=10,y=10+(30*i))
        Button(myframe,text="Accept").place(x=70,y=10+(30*i))

mybutton=Button(root,text="OK",command=myClick)
mybutton.place(x=420,y=10)

myvalue=Entry(root)
myvalue.place(x=450,y=10)

root.mainloop()

通常,当我创建一个label小部件时,我会这样做

代码语言:javascript
复制
mylabel=Label(root,text='mylabel')
mylabel.pack()

因此,当我稍后想要更改标签的文本时,我可以简单地这样做

代码语言:javascript
复制
mylabel.config(text='new text')

但是现在,既然我使用for循环来一次创建所有标签,那么在创建标签之后,有没有办法处理各个标签呢?例如,用户在输入框中键入'5‘,程序将给我5个标签+5个按钮。是否可以更改属性(例如,label.config(..))各个标签的?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-04-04 13:28:04

好的!只需创建一个标签列表,对每个标签调用place,然后您可以在以后引用它们并更改它们的值。如下所示:

代码语言:javascript
复制
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()

另请注意!在原始代码的赋值Mylabel=Label(myframe,text=" mytext "+str(i)).place(x=10,y=10+(30*i))中,该调用将Mylabel设置为None,因为place方法返回None。您希望将place调用分离到它自己的行中,如上面的代码所示。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15801199

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档