如何链接在for循环中创建的python tkinter小部件?
我想用for循环创建按钮和条目(state=disabled)小部件。要创建的小部件数量将是一个运行时参数。我想要的是,每次单击按钮时,相应的条目都将被启用(state=“normal”)。我代码中的问题是,我单击的任何按钮都只会影响最后一个条目小部件。有没有办法解决这个问题。?这是我的密码:如何链接在for循环中创建的python tkinter小部件?,python,python-3.x,tkinter,widget,Python,Python 3.x,Tkinter,Widget,我想用for循环创建按钮和条目(state=disabled)小部件。要创建的小部件数量将是一个运行时参数。我想要的是,每次单击按钮时,相应的条目都将被启用(state=“normal”)。我代码中的问题是,我单击的任何按钮都只会影响最后一个条目小部件。有没有办法解决这个问题。?这是我的密码: from tkinter import * class practice: def __init__(self,root): for w in range(5):
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()
代码中的几个问题-
按钮
和正在创建的条目,并将它们保存在一个实例变量中,最好将它们存储在一个列表中,然后w
将是列表中每个按钮/条目的索引lambda:something(some_param)
-直到实际调用函数时,some_param()
的函数值才被替换,此时,它正在处理entry1
的最新值,因此出现问题。您不应该依赖于此,而是应该使用并发送按钮/条目的索引来启用
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()
每当人们对使用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()
哇!这回答了我的问题!谢谢大家!@请注意,我在回答中提到的第一点很重要。否则你会陷入神秘的虫子中。