tkinter创建标签并动态托管

时间:2011-09-04 15:00:48

标签: python tkinter

我想创建一个简单的GUI,我可以在其中输入一些值。前面和下面的标签以及启动脚本的按钮。

我使用的是这样的东西:

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用于所有的命令时,我只能施放一次。但我需要我所有的数据; - )

我在想:

  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()

等等。我怎样才能使它发挥作用?

1 个答案:

答案 0 :(得分:7)

您的计划建议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()

然后,bodyfat条目的值为entry["bodyfat"].get()