Python函数不引用参数

Python函数不引用参数,python,function,tkinter,button,arguments,Python,Function,Tkinter,Button,Arguments,一个外观简单的Python函数让我很困扰。它与特金特有关。 请看以下代码: import tkinter as tk class Mainwindow(tk.Tk): def __init__(self, title="No title", size = "500x300"): tk.Tk.__init__(self) self.title(title) self.geometry(size) d

一个外观简单的Python函数让我很困扰。它与特金特有关。 请看以下代码:

import tkinter as tk

class Mainwindow(tk.Tk):
    def __init__(self, title="No title", size = "500x300"):
        tk.Tk.__init__(self)
        self.title(title)
        self.geometry(size)

def btn_func(i):
    print(f"Button {i} is clicked")

root = Mainwindow()

buttons = []
for i in range(0, 2):
    buttons.append(  tk.Button(root, text = f"Button {i}", command = lambda : btn_func(i) )  )
    buttons[i].pack()

root.mainloop()
我所期望的是,当我们单击按钮0时会看到“单击了按钮0”,而当单击按钮1时会看到“单击了按钮1”。但是不管我点击了什么按钮,结果总是“点击了按钮1”。
我无法找出代码中的错误点…

在循环之后,
I
始终为1。
btn_func
在定义时不使用
i
,而是在调用时使用。定义
lambda
时,需要传递实际的
i
。试试下面的方法

import tkinter as tk
import time

class Mainwindow(tk.Tk):
    def __init__(self, title="No title", size = "500x300"):
        tk.Tk.__init__(self)
        self.title(title)
        self.geometry(size)

def btn_func(i):
    print(f"Button {i} is clicked")

root = Mainwindow()

buttons = []
for i in range(0, 2):
    buttons.append(  tk.Button(root, text = f"Button {i}", command = lambda i=i: btn_func(i) )  )
    buttons[i].pack()


root.mainloop()