【问题标题】:loop only appends on last button循环仅附加在最后一个按钮上
【发布时间】:2016-04-08 16:35:43
【问题描述】:

我制作了一个带有可变数量的按钮和条目的 gui,这取决于早期的用户输入。我想将新条目存储在列表中。然而,我的循环只会附加循环中创建的最后一个条目。如何让每个按钮附加其各自的用户条目?

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 查看我上传的图片,右上角的“确定”按钮会附加条目。我希望左上角的按钮也附加它的相应条目。

【问题讨论】:

  • 为什么在for 循环中定义getFuseType??
  • 其实不确定。我只是把它从循环中拿出来,没有任何改变

标签: python for-loop append


【解决方案1】:

问题在于该函数没有围绕e 变量创建闭包,因此它们只会影响分配给e 的最新(最后一个)对象。如果你真的想这样做,你需要使用默认的 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)

【讨论】:

    【解决方案2】:

    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)
    

    【讨论】:

      猜你喜欢
      • 2016-08-25
      • 2019-05-15
      • 2019-07-08
      • 1970-01-01
      • 1970-01-01
      • 2021-03-19
      • 2016-02-22
      • 2015-06-08
      • 1970-01-01
      相关资源
      最近更新 更多