lambda 为全局变量赋值? [英] lambda to assign a value to global variable?

查看:47
本文介绍了lambda 为全局变量赋值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆