lambda赋值给全局变量? [英] lambda to assign a value to global variable?
问题描述
我正在使用tkinter并尝试在按下按钮时将值分配给全局变量.这是代码:
popup.add_command(label="Allow Moving Item", command=lambda: allowMoving=True)
我收到无效的语法.你能告诉我如何解决这个问题吗?
非常感谢!
I'm using tkinter and trying to assign a value to a global variable on a button press. Here is the code:
popup.add_command(label="Allow Moving Item", command=lambda: allowMoving=True)
I'm getting the invalid syntax. Can you tell me how to work this around?
Many thanks!
推荐答案
仅用于娱乐目的.
popup.add_command(label="Allow Moving Item",
command=lambda: globals().update(allowMoving=True))
(尽管记录的globals()
没有与locals()
相同的请勿修改返回值"警告,但我仍不确定这是否可以保证工作.)
(Although globals()
is not documented with the same "do not modify the return value" warning as locals()
, I'm still not sure this is guaranteed to work.)
一个更好的答案是改为使用def
语句定义回调.
A better answer would be to define the callback with a def
statement instead.
def set_allow_moving():
global allow_moving # Don't use camel case for variable names in Python
allow_moving = True
popup.add_command(label="Allow Moving Item", command=set_allow_moving)
这篇关于lambda赋值给全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!