以下是我的脚本。基本上,它会要求用户在输入框中输入一个数字。一旦用户输入一个数字并单击OK,它将根据用户在输入框中键入的数字给出Labels+Buttons组合。
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小部件时,我会这样做
mylabel=Label(root,text='mylabel')
mylabel.pack()因此,当我稍后想要更改标签的文本时,我可以简单地这样做
mylabel.config(text='new text')但是现在,既然我使用for循环来一次创建所有标签,那么在创建标签之后,有没有办法处理各个标签呢?例如,用户在输入框中键入'5‘,程序将给我5个标签+5个按钮。是否可以更改属性(例如,label.config(..))各个标签的?
发布于 2013-04-04 13:28:04
好的!只需创建一个标签列表,对每个标签调用place,然后您可以在以后引用它们并更改它们的值。如下所示:
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调用分离到它自己的行中,如上面的代码所示。
https://stackoverflow.com/questions/15801199
复制相似问题