Skip to main content
 首页 » 编程设计

python之破译 lambda 表达式

2024年10月01日8lyj

<分区>

我一直在密切关注 YouTube 视频,目的是使用 tkinter 创建屏幕键盘。

我了解大部分情况;在列表中创建我们的按钮并循环遍历这些按钮,在最佳位置插入行以创建美观的键盘。

我在执行此任务时遇到的唯一问题是,当我单击按钮时,按钮的文本会通过 tkinter 插入到输入框中。

我们执行此操作的方法是将命令分配给按钮,并在按下它时调用匿名函数,将我们按下的按钮分配给“x”参数。然后我们将此参数传递给另一个方法并将值插入到 Entry 小部件中。

我想明白,为什么我们不能只传入按钮本身,而是必须将按钮分配给一个参数...

self.textbox = textbox 
 
row=0 
col=0 
 
buttons = [ 
    '1','2','3','4','5','6','7','8','9','0', 
    'q','w','e','r','t','y','u','i','o','p', 
    'a','s','d','f','g','h','j','k','l', 
    'z','x','c','v','b','n','m','end'] 
 
for button in buttons: 
    # why not the following command instead? 
    # command = lambda: self.command(button) 
    command = lambda x=button: self.callback(x) 
    if button != 'end': 
        tk.Button(self, text=button, width=5, 
            command=command).grid(row=row, column=col) 
    col+=1 
    if col > 9: 
        col=0 
        row+=1 
 
def command(self, button): 
    x = button 
    self.callback(x) 
 
def callback(self, value): 
    self.textbox.insert(tk.END, value) 

使用上面的代码,我可以成功地将所需的值插入到我的条目小部件中。但是,如果我们使用我已注释掉的代码,它会改为将“end”插入条目小部件。

我试图将 lambda 函数复制到一个单独的方法中,但我仍然在我的入口小部件中插入一个“结束”。

# using the commented code above and passing in button as the parameter 
def command(self, button): 
    x = button 
    self.callback(x) 
 
def callback(self, value): 
    self.textbox.insert(tk.END, value) 

我想如果我能够将函数复制到非匿名函数中,那么它就可以工作,但显然不是。

我的 lambda 函数究竟在做什么,有没有办法通过使用非匿名函数(即方法)来复制它?