Python Tkinter OptionMenu将命令添加到多个OptionMenu [英] Python Tkinter OptionMenu add a command to multiple OptionMenus
问题描述
基本上,我有一系列的OptionMenu循环创建,但当前为空:
Basically I have a series of OptionMenus that are created in a loop, but is currently empty:
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()))
这可以正确地填充所有OptionMenu,但是当我在任何OptionMenu中选择一个值时,它只能设置option_menu [jj] [kk](即最后一个)。
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] (i.e. that last one made).
那我做错了什么?
推荐答案
这是一个涉及closur的非常常见问题es。请看以下示例:
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
全部为9。为什么?因为每个lambda函数都引用变量 x
。 x
在循环中的每次迭代中都会更改,但是它们仍然都引用同一对象。
The'll all be 9. Why? Because each lambda function refers to the variable x
. x
gets changed at every iteration through the loop, but they all still refer to the same object.
解决此问题的一种方法是使用默认参数。默认参数在创建函数时进行评估,而不是在调用函数时进行评估。
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
(做同一件事的另一种方法涉及 functools.partial
,您有时会看到... )
(another way to do the same thing involves functools.partial
which you'll see sometimes ...)
我经常想说-小心闭包。他们可能会有些棘手。
I often like to say -- "take care with closures". They can be a little tricky.
这篇关于Python Tkinter OptionMenu将命令添加到多个OptionMenu的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!