Lambda与Tkinter奇怪地工作 [英] lambda working oddly with tkinter

查看:52
本文介绍了Lambda与Tkinter奇怪地工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Tkinter制作计算器.我一直在尝试清理一下代码,但是遇到了麻烦.创建按钮时,我使用以下代码:

I am trying to make a calculator using Tkinter. I have been trying to clean up the code a bit but have run into a snag. When creating buttons, I use the following code:

Button(self,text="1",command=lambda: self.addkey("1"),width=self.defaultwidth,height=self.defaultheight).grid(row=5, column=0)
Button(self,text="2",command=lambda: self.addkey("2"),width=self.defaultwidth,height=self.defaultheight).grid(row=5, column=1)
Button(self,text="3",command=lambda: self.addkey("3"),width=self.defaultwidth,height=self.defaultheight).grid(row=5, column=2)

以下是名为

def addkey(self,key):
            # Adds a given key to the display
            if len(self.displaytext) + len(key) <= self.maxlength:
                self.displaytext += key
                self.display["text"] = self.displaytext

按顺序按下按钮1、2和3时,输出如下:

When buttons 1, 2, and 3 are pressed in that order, the following is the output:

123

我一直在尝试清理代码,使其看起来更像:

I have been trying to clean up the code so that it looks more like:

for i in range(3):
    Button(self,text=str(i+1),command=lambda: self.addkey(str(i+1)),width=self.defaultwidth,height=self.defaultheight).grid(row=5, column=i)

这将按钮添加得很好,但是按该顺序按下1、2和3时,屏幕上将显示以下内容:

This adds the buttons fine, but when 1, 2, and 3 are pressed in that order, the following shows up on the screen:

333

我想知道我是否错过了某件事,或者根本不可能做到这一点.

I was wondering if I missed something or this is simply not possible.

推荐答案

嗯,范围很广.当您这样做时:

Ah, scoping. When you do this:

command=lambda: self.addkey(str(i))

您不是i解析"为一个数字,然后是.您只是在告诉lambda在调用i时引用此后.

You're not "resolving" the i to a number right there and then. You're just telling the lambda to reference i when it's invoked, afterwards.

for循环结束后的任何时间,i = 3(最后一个值),因此当您的所有lambda要求输入i时,它们都会得到3.

At any time past the end of the for loop, i = 3 (last value), so all of your lambdas get 3 when they ask for i.

如果我没记错的话,可以添加一个函数作为间接手段,它将适当地从周围的范围捕获" i.

If I'm not mistaken, you can add a function as means of indirection, and it will appropriately "capture" i from the surrounding scope.

def add_key_f(i):
    return lambda self: self.addkey(i)

这篇关于Lambda与Tkinter奇怪地工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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