我只是把手放在SHA2017徽章上。我编写了以下程序并在模拟器中运行它:
import ugfx
import badge
def key_pressed(key, is_pressed):
print('key_pressed(key=%r, is_pressed=%r)' % (key, is_pressed))
badge.init()
ugfx.init()
ugfx.input_init()
for key in [ugfx.JOY_LEFT, ugfx.JOY_UP, ugfx.JOY_RIGHT, ugfx.JOY_DOWN]:
ugfx.input_attach(key, (lambda is_pressed: key_pressed(key, is_pressed)))
# Uncommenting this makes all keystrokes get interpreted as JOY_UP:
# ugfx.input_attach(key, (lambda is_pressed: key_pressed(key, is_pressed)))
# But uncommenting this makes JOY_UP work as intended and doesn't affect other keys
# ugfx.input_attach(ugfx.JOY_UP, (lambda is_pressed: key_pressed(ugfx.JOY_UP, is_pressed)))
while True:
pass
如果我运行它,按任意键都会说我按下了JOY_DOWN。取消注释第一行将使所有人说我按下了JOY_UP并且仅取消注释最后一个注释行将使所有键激活JOY_DOWN,除了JOY_UP,它按预期工作。
这是一个错误还是预期的行为?似乎MicroPython只编译lambda一次并将引用绑定到“key”,这对我来说似乎很奇怪。
答案 0 :(得分:1)
问题是变量key
已更新,因此 lambda 表达式中的所有引用也会更新:
您还需要确定范围key
:
for key in [ugfx.JOY_LEFT, ugfx.JOY_UP, ugfx.JOY_RIGHT, ugfx.JOY_DOWN]:
ugfx.input_attach(key,lambda k: (lambda is_pressed: key_pressed(k, is_pressed)(key)))
或者您可以使用:
from functools import partial
for key in [ugfx.JOY_LEFT, ugfx.JOY_UP, ugfx.JOY_RIGHT, ugfx.JOY_DOWN]:
ugfx.input_attach(key,partial(lambda k, is_pressed: key_pressed(k, is_pressed),key))
或使用默认值:
from functools import partial
for key in [ugfx.JOY_LEFT, ugfx.JOY_UP, ugfx.JOY_RIGHT, ugfx.JOY_DOWN]:
ugfx.input_attach(key,lambda is_pressed, k=key: key_pressed(k, is_pressed)))