我正在使用 for 循环从 item_list 创建一行 3x3 的按钮。我希望能够按下每个按钮并显示其独特的价格。当我运行 print_price 时,它返回 3.50。我知道这是因为 3.50 是赋予按钮的最新值,但我无法解决此问题。我基本上是想找到一种方法,让在 for 循环中制作的按钮有自己的命令。
def print_price(item):
print(item_list[item])
item_list = dict(apple=1.20, fish=2.40, chocolate=1.20, butter=2.40, hat = 10.00, socks
= 5.70, eggs = 4.00, burgers = 3.50)
#
row_index = 0
column_index = 0
for item in item_list:
tk.Button(item_frame, text=item, height=4,
width=6,command=lambda:print_price(item)).grid(row=row_index, column=column_index)
column_index += 1
if column_index == 3:
row_index += 1
column_index = 0
if column_index == 6:
row_index += 1
column_index = 0
是的,你需要做的就是让你的 lambda 函数接受一个关键字参数,然后将默认参数值设置为项目的值,然后它将存储每个单独回调的值。所以不是
lambda: print_price(item)
而是lambda x=item: print_price(x)
.
例如
def print_price(item):
print(item_list[item])
item_list = dict(apple=1.20, fish=2.40, chocolate=1.20, butter=2.40, hat = 10.00, socks
= 5.70, eggs = 4.00, burgers = 3.50)
row_index = 0
column_index = 0
for item in item_list:
tk.Button(item_frame, text=item,
height=4, width=6,
command=lambda x=item: print_price(x)).grid(
row=row_index, column=column_index)
column_index += 1
if column_index == 3:
row_index += 1
column_index = 0
if column_index == 6:
row_index += 1
column_index = 0