2011-09-04 60 views
1

我想創建一個簡單的GUI,可以輸入一些值。在之前和之後的標籤以及用於啓動腳本的按鈕。tkinter創建標籤並動態地輸入

我用的是這樣的:

w = Label(master, text="weight:") 
w.grid(sticky=E) 
w = Label(root, text="bodyfathydrationmuscle:bones") 
w.grid(sticky=E) 
w = Label(root, text="hydration:") 
w.grid(sticky=E) 

其確定,但我想這樣做動態。另外當我將w用於所有的entrys時,我只能使用w.get一次。但我需要我的所有數據;-)

我在想:

def create_widgets(self): 
    L=["weight","bodyfat","hydration","muscle","bones"] 
    LV=[] 
    for index in range(len(L)): 
     print(index) 
     print(L[index]) 
     ("Entry"+L[index])= Entry(root) 
     ("Entry"+L[index]).grid(sticky=E) 
     ("Label"+L[index])=Label(root, text=L[index]) 
     ("Label"+L[index]).grid(row=index, column=1) 

以後要撥打:

var_weight=Entryweight.get() 
var_bodyfat=Entrybodyfat.get() 

等。我怎樣才能使它工作?

回答

6

你的程序建議Entrybodyfat和其他變量應該是generated on the fly,但你不想這樣做。

正常的方法是將條目和標籤存儲在列表或地圖:

from Tkinter import * 

root = Tk() 

names = ["weight", "bodyfat", "hydration", "muscle", "bones"] 
entry = {} 
label = {} 

i = 0 
for name in names: 
    e = Entry(root) 
    e.grid(sticky=E) 
    entry[name] = e 

    lb = Label(root, text=name) 
    lb.grid(row=i, column=1) 
    label[name] = lb 
    i += 1 

def print_all_entries(): 
    for name in names: 
     print entry[name].get() 

b = Button(root, text="Print all", command=print_all_entries) 
b.grid(sticky=S) 

mainloop() 

的體脂項的值是那麼entry["bodyfat"].get()