[英]loop only appends on last button
I've made a gui with a variable amount of buttons and entries, dependent on earlier user inputs. 我已经制作了一个gui,它具有可变数量的按钮和条目,具体取决于早期的用户输入。 I want to store the new entries in a list. 我想将新条目存储在列表中。 My loop however will only append the last entry created in the loop. 但是,我的循环将仅追加在循环中创建的最后一个条目。 How can I get each button to append it's respective user entry? 如何获取每个按钮以附加其各自的用户条目?
def getFuseType():
(Fuse.fuseType).append(e.get()
print(Fuse.fuseType)
for i in range(1,int(Site.NoFuses)+1):
l = Label(FuseWindow, text = "Fuse Type")
e = Entry(FuseWindow)
l.grid(row = 1, column = i+3)
e.grid(row = 2, column = i+3)
b = Button(FuseWindow, text = "ok", command = getFuseType)
b.grid(row = 3, column = i+3)
Fuse GUI see the image I've uploaded, The top right 'OK' button appends the entry. 保险丝GUI可以看到我上传的图像,右上方的“确定”按钮将附加条目。 I want the top Left button to also append it's respective entry. 我希望顶部的“左”按钮也附加其相应的条目。
The problem is that the function isn't creating a closure around the e
variable so they only affect the most recent (last) object assigned to e
. 问题在于该函数未在e
变量周围创建闭包,因此它们仅影响分配给e
最新(最后)对象。 If you really want to do this you'll need to use a defaulted arg.. 如果您确实要执行此操作,则需要使用默认的arg ..
for i in range(1,int(Site.NoFuses)+1):
l = Label(FuseWindow, text = "Fuse Type")
e = Entry(FuseWindow)
l.grid(row = 1, column = i+3)
e.grid(row = 2, column = i+3)
def getFuseType(e=e):
(Fuse.fuseType).append(e.get())
print(Fuse.fuseType)
b = Button(FuseWindow, text = "ok", command = getFuseType)
b.grid(row = 3, column = i+3)
Get getFuseType
out of the for
, it is defined every loop iteration and hence you only get the last create entry e
从for
获取getFuseType
,它是在每次循环迭代中定义的,因此,您只会获得最后的创建条目e
def getFuseType(ent):
Fuse.fuseType.append(ent)
print(Fuse.fuseType)
for i in range(1,int(Site.NoFuses)+1):
l = Label(FuseWindow, text = "Fuse Type")
e = Entry(FuseWindow)
ent = e.get()
l.grid(row = 1, column = i+3)
e.grid(row = 2, column = i+3)
b = Button(FuseWindow, text = "ok", command = lambda ent = ent:getFuseType(ent))
b.grid(row = 3, column = i+3)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.