首页 > 解决方案 > 在使用 tkinter Button 小部件在 python 中传递参数时需要帮助

问题描述

我正在读取一个 51 行 4 列的 csv 文件。我已将其存储在尺寸为 51 X 4 的 2D 列表中。我的目标是创建 51 个按钮,并且每次都将元素的值传递给由此创建的列表的 list[i][1] 作为其参数。但是,在这段代码中,list[50][1] 的值被传入所有 51 个按钮。如何将所需的不同 list[i][1] 值作为参数传递给每个第 i 个按钮?

这是我的代码。请找出其中的错误,非常感谢您的帮助。谢谢你。

file = open('stocklist.csv', 'r')
reader = csv.reader(file)

stocks = []
for line in reader:
    w = line[0]
    x = line[1]
    y = line[2]
    z = line[3]

    stocks.append([w, x, y, z])

height = 51
width = 4

for i in range(height):
    b = tk.Button(f, text=stocks[i][1], command=lambda: open_link(stocks[i][1]))
    b.grid(row=i, column=1)
    print(b)

标签: pythonbuttontkinterparameter-passing

解决方案


您可以使用 functool 的partial链接):

b = tk.Button(f, text=stocks[i][1], command=partial(open_link,stocks[i][1])


推荐阅读