【问题标题】:How do I link python tkinter widgets created in a for loop?如何链接在 for 循环中创建的 python tkinter 小部件?
【发布时间】:2015-08-16 17:07:23
【问题描述】:

我想用 for 循环创建 Button 和 Entry(state=disabled) 小部件。要创建的小部件数量将是运行时参数。我想要的是每次单击按钮时,相应的条目都会变为启用状态(状态=“正常”)。我的代码中的问题是我单击的任何按钮,它只影响最后一个条目小部件。有没有什么办法解决这一问题。?这是我的代码:

from tkinter import *

class practice:
    def __init__(self,root):
        for w in range(5):
            button=Button(root,text="submit",
                command=lambda:self.enabling(entry1))
            button.grid(row=w,column=0)
            entry1=Entry(root, state="disabled")
            entry1.grid(row=w,column=1)

    def enabling(self,entryy):
        entryy.config(state="normal")

root = Tk()
a = practice(root)
root.mainloop()

【问题讨论】:

    标签: python python-3.x tkinter widget


    【解决方案1】:

    您的代码中存在一些问题 -

    1. 您应该保留 buttons 和您正在创建的条目并将它们保存在实例变量中,很可能最好将它们存储在 list 中,然后 w 将是每个按钮的索引/条目在列表中。

    2. 当你做 lambda: something(some_param) 时 - some_param() 的函数值不会被替换,直到函数被实际调用,那时它正在处理 entry1 的最新值,因此问题。您不应该依赖它,而应该使用functools.partial() 并发送Button/Entry 的索引来启用。

    例子-

    from tkinter import *
    import functools
    
    class practice:
        def __init__(self,root):
            self.button_list = []
            self.entry_list = []
            for w in range(5):
                button = Button(root,text="submit",command=functools.partial(self.enabling, idx=w))
                button.grid(row=w,column=0)
                self.button_list.append(button)
                entry1=Entry(root, state="disabled")
                entry1.grid(row=w,column=1)
                self.entry_list.append(entry1)
    
        def enabling(self,idx):
                self.entry_list[idx].config(state="normal")
    
    
    root = Tk()
    a = practice(root)
    
    root.mainloop()
    

    【讨论】:

    • 哇。这回答了我的问题!谢谢!
    • @Crstn 请注意,我说的第一点(在我的回答中)很重要。否则你最终会遇到神秘的错误。
    【解决方案2】:

    每当人们对使用 lambda 表达式而不是 def 语句创建的函数有问题时,我建议使用 def 语句重写代码,直到它正常工作。这是对您的代码最简单的修复:它重新排序小部件的创建并将每个条目绑定到一个新函数作为默认参数。

    from tkinter import *
    
    class practice:
        def __init__(self,root):
            for w in range(5):
                entry=Entry(root, state="disabled")
                button=Button(root,text="submit",
                    command=lambda e=entry:self.enabling(e))
                button.grid(row=w,column=0)
                entry.grid(row=w,column=1)
    
        def enabling(self,entry):
            entry.config(state="normal")
    
    root = Tk()
    a = practice(root)
    root.mainloop()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-04
      • 2021-10-15
      • 1970-01-01
      • 2022-01-10
      相关资源
      最近更新 更多