如何显示条目小部件列表中的内容?

时间:2018-02-07 07:39:23

标签: python tkinter tk

我编写了一个代码,其中LabelEntry小部件'变量放在一个列表中(为了避免创建每个Label所需的行数和Entry小部件)。然后使用for循环来创建LabelEntry小部件,使用提交按钮,其必须列出每个Entry小部件的条目。但是显示空值而不是显示输入的值。任何人都可以帮助我知道原因并更正代码。

以下是我写的代码:

from Tkinter import *
app = Tk()

list1 = ['l1','l2','l3']
list2 = ['e1','e2','e3']

entries = []

r = 0
c = 0
for m,n in zip(list1, list2):
    x = Label(app, text=m)
    x.grid(row = r, column =c)

    n = StringVar()
    e = Entry(app, textvariable = n)
    e.grid(row =r , column = c+1)

    entries.append(e.get())
    r = r + 1



def func():
    entries.append("Dfg")
    print entries

s = Button(app, text = "Submit", command = func)
s.grid(row = r, columnspan=2)

app.minsize(400, 400)
app.mainloop()

请注意:发布代码时可能会出现缩进问题,不便之处。

1 个答案:

答案 0 :(得分:1)

for loop用于初始化,在这种情况下,当创建条目时,Entry的输入为空,所以当entries.append(e.get())为空时 。我从你的代码中改了一些东西,单击按钮BTW我用python3代替python2

时输入值
from tkinter import *
app = Tk()

list1 = ['l1','l2','l3']
list2 = ['e1','e2','e3']

entries = []
e = []
r = 0
c = 0
for index, m in enumerate(zip(list1, list2)):
    x = Label(app, text=m)
    x.grid(row = r, column =c)

    n = StringVar()
    e.append( Entry(app, textvariable = n))
    e[index].grid(row =r , column = c+1)
    r = r + 1

def func():
    entries = []
    for a in e:
      entries.append(a.get())
    print(entries)

s = Button(app, text = "Submit", command = func)
s.grid(row = r, columnspan=2)

app.minsize(400, 400)
app.mainloop()