Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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: allowMoving=True)

I'm getting the invalid syntax. Can you tell me how to work this around?

like image 224
sssseossss Avatar asked Sep 09 '26 12:09

sssseossss


2 Answers

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)
like image 78
chepner Avatar answered Sep 11 '26 02:09

chepner


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)
like image 32
Bryan Oakley Avatar answered Sep 11 '26 02:09

Bryan Oakley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!