Lambda To Assign A Value To Global Variable?
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: allowMovin
Solution 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)
Solution 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)
Post a Comment for "Lambda To Assign A Value To Global Variable?"