2011-09-04 69 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()