tkinter 动态创建标签和输入框

2 投票
1 回答
16499 浏览
提问于 2025-04-17 01:24

我想创建一个简单的图形界面,可以在里面输入一些值。界面上有一个标签在前面和后面,还有一个按钮来启动脚本。

我之前使用的是这样的代码:

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

等等。我该怎么做才能实现呢?

1 个回答

9

你的程序建议将 Entrybodyfat 和其他变量动态生成,也就是在运行时创建这些变量,但你不想这样做。

通常的做法是把输入和标签存放在一个列表或者字典里:

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() 来获取。

撰写回答