【问题标题】:A Python function does not refer to the argument [duplicate]Python函数不引用参数[重复]
【发布时间】:2021-01-13 13:09:31
【问题描述】:

一个看起来很简单的 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 被单击” . 我无法找出代码中的错误点...

【问题讨论】:

    标签: python function tkinter button arguments


    【解决方案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()
    

    【讨论】:

      猜你喜欢
      • 2019-05-24
      • 1970-01-01
      • 2014-10-13
      • 1970-01-01
      • 2018-01-09
      • 2018-11-12
      • 2020-12-12
      • 2013-07-13
      • 1970-01-01
      相关资源
      最近更新 更多