python - 通过 lambda 将变量传递到函数 Tkinter

标签 python class lambda callback tkinter

我对以下代码的问题是将“i”(只是一个简单的数字范围,但根据 number_boxes 进行更改)通过 lambda 传递给回调,以便为创建的每个框提供单独的功能。

我尝试阅读教程并在代码中尝试各种操作,但它要么不起作用,要么收到错误“lambda() 仅需要 2 个参数,给定 3 个参数”等。我相信我需要制作“i”一个列表,但我仍然收到这个特定的错误..

我已经对出现问题的代码进行了评论。我需要返回每个框中的值并覆盖文本。

谢谢。

self.clicked = [] # In my __init__ definition
self.numbers = [StringVar() for i in xrange(self.number_boxes) ]   # Create Stringvar for each box

for i in xrange(self.number_boxes): # For each number, create a box

        self.clicked.append(False) # Not clicked in yet
        self.box.append(Entry(self.frame_table,bg='white',borderwidth=0, width=10, justify="center", textvariable=self.numbers[i], fg='grey')) # Textvariable where I enter a value to get after, need to do for each box (use box[i] but cannot for append)
        self.box[i].grid(row=row_list,column=column+i, sticky='nsew', padx=1, pady=1) 
        self.box[i].insert(0, "Value %g" % float(i+1))
        self.box[i].bind("<Button-1>", lambda event, index=i : self.callback(event, index)) # Need to pass the 'i's' to callback but having lambda difficulties

for i in self.numbers: 
        i.trace('w',lambda index=i: self.numberwritten(index) ) # Need for each box again here

def numberwritten(self, index): # A way of combining numberwritten and callback?
    po = self.box[index].get() # Get the values in each box
    print po

def callback(self, event, index):
        if (self.clicked[index] == False): # When clicked in box, overwrite default text with value and change colour to black, not grey
            self.box[index].delete(0, END)
            self.box[index].config(fg='black')
                self.clicked[index] = True

更新:当前问题:需要将“i”的所有值传递给回调,而不仅仅是一个,但如何将列表放入 lambda?

错误:

Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python26\lib\lib-tk\Tkinter.py", line 1410, in __call__
return self.func(*args)
TypeError: lambda() takes at most 1 argument (3 given)

最佳答案

您的代码非常接近,但是这一行:

self.box[i].bind("<Button-1>", lambda self, event,i : self.callback(event, data))

应该是

self.box[i].bind("<Button-1>", lambda event, index=i: self.callback(event, index))

对象index只是一个任意标签,我们为其分配i的值。请注意,如果我们传递 i 而不是变量名,Python 会抛出错误。而且我们不需要传递 self;它通过在函数调用中使用而隐式传递:self.callback()

我唯一的其他评论是,您应该将 clicked 转换为列表,以便您可以跟踪用户选择的对象。您可以按照 box 的形成方式来形成它。祝你好运。


这里有一些关于将 clicked 转换为列表的提示,因为我认为这是您当前遇到的问题。 编辑:根据 J.F. Sebastian 的评论更改了几行。

# Create an empty list based on the number of boxes created 
# above. This could go in your class's __init__ function, 
# or it could be declared globally, depending on the scope
# of self.box and the loop which determines its length.
self.clicked = ([False] * len(self.box))

# Finally, in your callback, check one member of the list,
# depending on which box was clicked.
def cb(self, event, index):
    if not self.clicked[index]:
        self.box[index].delete(0, END)
        self.box[index].config(fg='black')
        self.clicked[index] = True
    # Print the value of each of the widgets stored in the box list.
    for i, j in enumerate(self.box):
        print("%ith element: %s" % (i, j.get()))  

关于python - 通过 lambda 将变量传递到函数 Tkinter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11345810/

相关文章:

python - 如何使用 sqlalchemy 查询具有值的数据库以获取另一个值?

python - 在 pymc3 中重写用于动态系统参数估计的 pymc 脚本

c++ - 错误 LNK2001 : unresolved external symbol - when creating abstract class c++

python - 如何优雅/高效地为需要大量实例变量的 Python 类编写 __init__ 函数?

java - 使用 Java 8,创建排序和分组字符串列表的最简洁方法是什么

lambda - Terraform cloudwatch 保留逻辑

java - 如何在 Java 8 流上运行嵌套收集

python - 为什么 np.corrcoef(x) 和 df.corr() 给出不同的结果?

Python 截断方法大小参数行为

php - 无法从 $class 获取静态变量