Python-Tkinter,Combobox-使用Lambda函数传递2个参数 [英] Python-Tkinter,Combobox - Passing 2 parameters using Lambda function
问题描述
背景:
GUI表具有跳过组合框窗口小部件,允许用户跳过当前行的执行。此GUI中的行数有所不同。
A GUI table having a "skip combobox" widget allowing user to skip current line from executing. Amount of lines in this GUI varies. This "skip" is created using a for loop.
当选择 on或 off时, bind
进程执行称为 self.but_callback
的方法,该方法执行其余代码。
When selecting "on" or "off" a bind
process executes a method called self.but_callback
which doing the rest of code.
目标:
将 i
值传递给 self.but_callback
,以及绑定
所需的事件
。
Pass i
value to self.but_callback
, along with event
needed to bind
.
代码下面显示了尝试将 i
值直接传递到 self.but_callback(event,i)
BUT 而不是分配正确的 i
值,而是为每个创建的 skip_button
传递for循环的最后一个值。
Code below, shows a try to pass i
value directly into self.but_callback(event,i)
BUT instead of assigning the right i
value it passes the last value of for loop for every skip_button
created.
问题:当有2个参数时,如何在循环中传递正确的 i
值需要使用 lambda
函数传递。
Question: How to pass correct i
value while in a loop, when 2 parameters are need to pass using lambda
function.
未找到结合两个问题的答案。
Did not find any answer combining both issues.
for i in range(len(data_from_file)):
#Skip button
self.var.append(tk.StringVar())
self.var[7].set('On')
skip_button = ttk.Combobox(inner_frame, width=5, textvariable=self.var[7], values=['On','Off'],state='readonly', justify=tk.CENTER)
skip_button.bind('<<ComboboxSelected>>',lambda event: self.but_callback(event,i))
skip_button.grid(row=i+1, column=7, padx=8)
def but_callback(self,event,x):
print(x)
推荐答案
lambda
循环。
它不会在您复制 i
中的值时复制创建 lambda
函数,但仍引用 i
。因此,所有函数都引用相同的变量(在内存中的相同位置),并且在执行时会从 i
获取值。
It doesn't copy value from i
when you create lambda
function but it keeps reference to i
. So all functions have reference to the same variable (the same place in memory) and they get value from i
when they are exceuted.
您必须将 i
分配给 lambda
中的参数(例如 x = i
),然后在函数中使用此参数 x
。这样,它将从 i
复制当前值并在 lambda
函数中使用
You have to assign i
to argument in lambda
(for example x=i
) and use this argument x
in your function. This way it will copy current value from i
and use in lambda
function
lambda event, x=i : self.but_callback(event, x)
这篇关于Python-Tkinter,Combobox-使用Lambda函数传递2个参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!