1

I am using a for loop to create a 3x3 row of buttons from the item_list. I want to be able to press each button and have their unique price display. When I run print_price it returns 3.50. I understand this is because 3.50 is the most recent value given to the button but I cant fix this problem. I am basically trying to find a way to give buttons made in a for loop their own command.

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
SuperStormer
  • 4,997
  • 5
  • 25
  • 35

1 Answers1

0

Yes, All you need to do is make your lambda function accept a keyword argument, and then set the default argument value to be the value of the item, which will then store the value for each individual callback. So instead of lambda: print_price(item) it would be lambda x=item: print_price(x).

For example:

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
Alexander
  • 16,091
  • 5
  • 13
  • 29