Skip to main content
 首页 » 编程设计

python之tkinter 动态创建标签和条目

2025年05月04日14powertoolsteam

我想创建一个简单的 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 用于所有条目时,我只能投一次 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() 

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

请您参考如下方法:

您的程序建议 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()。