首页 > 解决方案 > Python 函数不引用参数

问题描述

一个看起来很简单的 Python 函数让我很困扰。它与 Tkinter 有关。看下面的代码:

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 被单击”。我无法找出我的代码中的错误点......

标签: pythonfunctiontkinterbuttonarguments

解决方案


在循环之后,i始终为 1。定义时btn_func不使用i,而是在调用时使用。在i定义lambda. 尝试以下

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()

推荐阅读