如何链接在 for 循环中创建的 python tkinter 小部件? [英] How do I link python tkinter widgets created in a for loop?

查看:30
本文介绍了如何链接在 for 循环中创建的 python tkinter 小部件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to create Button and Entry(state=disabled) widgets with a for loop. The number of widgets to be created will be a runtime argument. What I want is that every time I click the button, the corresponding entry will become enabled(state="normal"). The problem in my code is that any button I click, it only affects the last entry widget. Is there anyway to fix this.? Here is my code:

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()

推荐答案

代码中的几个问题 -

Few issues in your code -

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

  1. You should keep the buttons and entries you are creating and save them in an instance variable, most probably it would be good to store them in a list , then w would be the index for each button/entry in the list.

当你执行 lambda: something(some_param) - some_param() 的函数值不会被替换,直到函数被实际调用,并且当时,它正在处理 entry1 的最新值,因此出现了问题.你不应该依赖它,而应该使用 functools.partial() 并传入Button/Entry的索引来启用.

When you do lambda: something(some_param) - the function value of some_param() is not substituted, till when the function is actually called, and at that time, it is working on the latest value for entry1 , hence the issue. You should not depend on that and rather you should use functools.partial() and send in the index of Button/Entry to enable.

示例 -

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()

这篇关于如何链接在 for 循环中创建的 python tkinter 小部件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆