python - 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 被单击”。我无法找出我的代码中的错误点......
解决方案
在循环之后,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()
推荐阅读
- magento - 更改购物车中的产品名称,报价单,发票 Magento 2
- php - docker 中的 Composer 私有存储库
- r - 在 R 过滤器中,一个表的行基于与另一个表的匹配和日期小于另一个表
- json - 如何将 I18n 实现为 JPA 或 Hibernate 实体的 JSON 对象?
- bash - 自定义编写的 Nagios 插件总是返回不正确的值,但在命令行上工作
- sql - postgresql - 将间隔格式化为具有大量小时数的时间
- javascript - 如何检测浏览器的chrome
- html - css 属性掩码不适用于 svg
- python - 使用 numpy 的逐行矩阵乘法
- python - 从 python 控制台菜单获取返回值