lambda to assign a value to global variable?

风格不统一 提交于 2019-12-24 01:56:14

问题


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!


回答1:


For entertainment purposes only.

popup.add_command(label="Allow Moving Item",
                  command=lambda: globals().update(allowMoving=True))

(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.)


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)



回答2:


Don't use lambda. A good rule of thumb is to never use lambda unless there's simply no other way. The use of lambda in callbacks should be the exception rather than the rule.

def allow_moving():
    global allowMoving
    allowMoving = True

popup.add_command(label="Allow Moving Item", command=allow_moving)


来源:https://stackoverflow.com/questions/42211594/lambda-to-assign-a-value-to-global-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!