我的程序中出现奇怪的错误,我不知道如何解释
我正在 wxpython 中编写一个简单的剪贴板管理器,以获取乐趣和利润,并且我遇到了一个特殊的错误,该错误导致无论单击哪个菜单项都会调用相同的函数。
代码在 这里,问题与第 49-56 行有关(“Clear”项目工作得很好) - 它总是调用最后创建的函数。
我尝试打印正在创建的 lambda 函数、菜单项、它的 ID - 几乎所有我能想到的都可能是问题的根源,但我没有找到任何线索。
如果我无法选择菜单项,我会有点困惑,所以我将不胜感激所有帮助。
I'm writing a simple clipboard manager in wxpython for fun and profit and I've run across a peculiar bug that is causing the same function to be called no matter which menu item is clicked.
The code is here and problem is related to lines 49-56 (the "Clear" item works just fine) - it always calls the last function created.
I tried printing the lambda function being created, the menu item, it's ID - pretty much everything that I could think of that could have been the source of problem, but I didn't find any clues.
I'm kinda stuck if I can't choose menu items so I'd appreciate all and any help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
i
的值在CreateHistoryMenu
的封闭范围内查找。当调用func
时,i
等于循环中的最后一个值。这就是为什么菜单项都调用最后创建的函数的原因。如果将
i
添加到具有默认值的lambda
参数中,i
将成为lambda
中的局部变量code> 本身,具有在定义 lambda 时绑定的默认值。这将是i
的正确值:The value of
i
is being looked-up in the enclosing scope ofCreateHistoryMenu
. When thefunc
is called,i
equals the last value in the loop. That is why the menu items all call the last function created.If you add
i
to the arguments of thelambda
with a default value,i
will become a local variable in thelambda
itself, with a default value which was bound at the time the lambda was defined. This will be the right value fori
: