[英]Tkinter: Addressing Label widget created by for loop
以下是我的腳本。 基本上,它會要求用戶在輸入框中輸入一個數字。 用戶輸入一個數字並單擊“確定”后,它會根據用戶在“輸入”框中輸入的數字為您提供標簽+按鈕的組合。
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()
通常,當我創建一個標簽小部件時,我會做這樣的事情
mylabel=Label(root,text='mylabel')
mylabel.pack()
因此,當我稍后想更改標簽的文本時,我可以簡單地執行此操作
mylabel.config(text='new text')
但是現在,由於我正在使用 for 循環一次創建所有標簽,那么在創建標簽后是否還有解決各個標簽的問題? 例如,用戶在輸入框中輸入“5”,程序會給我 5 個標簽 + 5 個按鈕。 無論如何,我是否可以更改單個標簽的屬性(即 label.config(..))?
當然! 只需列出標簽列表,在每個標簽上調用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=Label(myframe,text=" mytext "+str(i)).place(x=10,y=10+(30*i))
中,該調用將Mylabel
設置為 None,因為place
方法返回 None。 您想將place
調用分成自己的一行,就像上面的代碼一樣。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.