[英]Python Tkinter OptionMenu add a command to multiple OptionMenus
Basically I have a series of OptionMenus that are created in a loop, but is currently empty: 基本上我有一系列在循环中创建的OptionMenus,但目前是空的:
option_menu = []
for ii in range(jj):
option_menu.append([])
for ll in range(kk):
option_menu[ii].append(OptionMenu(frame,tkinter_text_var[ii][ll],''))
Then elsewhere I use a checkbox to set the values along the lines of: 然后我在其他地方使用复选框来设置以下行的值:
for ii in range(jj):
for ll in range(kk):
option_menu[ii][ll]["menu"].add_command(label = name_from_box.get(), command = lambda: tkinter_text_var[ii][ll].set(name_from_box.get()))
This works to populate all of the OptionMenus properly, but when I select a value in any of the OptionMenus, it only sets option_menu[jj][kk] (ie that last one made). 这适用于填充所有OptionMenus,但是当我在任何OptionMenus中选择一个值时,它只设置option_menu [jj] [kk](即最后一个)。
So what have I done wrong? 那我做错了什么?
This is a very common question involving closures. 这是一个涉及闭包的非常常见的问题。 Look at the following example:
请看以下示例:
alist = [lambda : x for x in range(10) ]
print (alist[2]()) #9
print (alist[4]()) #9
The'll all be 9. Why? 这些都是9.为什么? Because each lambda function refers to the variable
x
. 因为每个lambda函数都引用变量
x
。 x
gets changed at every iteration through the loop, but they all still refer to the same object . x
在循环的每次迭代中都会被更改,但它们仍然引用同一个对象 。
One way around this is to use a default argument. 解决此问题的一种方法是使用默认参数。 Default arguments are evaluated when the function is created, not when it is called.
创建函数时会计算默认参数,而不是在调用函数时计算默认参数。
alist = [lambda y=x: y for x in range(10) ]
print (alist[2]()) #2
print (alist[4]()) #4
(another way to do the same thing involves functools.partial
which you'll see sometimes ...) (做同样事情的另一种方法涉及
functools.partial
,你有时会看到......)
I often like to say -- "take care with closures". 我经常喜欢说 - “小心关闭”。 They can be a little tricky.
它们可能有点棘手。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.