-1

I am attempting to make a turn-based combat system, and I ran into a problem while trying to get buttons to access elements of a list relatively (the button in a list of buttons accesses an element of the same index in another list). However when clicked, each button only accesses the last element of the list. Here is simplified sample code that exhibits the same problem:

from tkinter import *

root = Tk()

my_list = ['index 0', 'index 1', 'index 2']
buttons = []

for i in range(len(my_list)):
    buttons.append(Button(root, text='Button '+str(i), command=lambda: print(my_list[i])))
    buttons[i].pack()

I understand that since I am doing this in a loop, the last element is probably being accessed by all buttons because it is the most recent value of i, but I can't figure out another way to accomplish my goal. To be more specific and draw from the example code above, my_list represents a list of actions that a character can take. Each button in buttons corresponds to one of those actions (clicking the button sets the action you take at the end of the turn). Normally, I could probably assign the actions more explicitly, but since there are multiple fighters I opted to use a loop and do it implicitly since my_list changes frequently to reflect the actions of each different fighter.

I am not very clear on why this is happening, and I would also like to know how I can accomplish my goal of allowing each button to access its corresponding element in my_list since it probably cannot be done in this way. Thank you for reading and let me know if I can clarify anything for you.

PlatypusVenom
  • 547
  • 2
  • 6
  • 12

1 Answers1

0

Use functools.partial instead of lambda:

from functools import partial
# ...
buttons.append(Button(root, text='Button '+str(i), command=partial(print, my_list[i])))
Novel
  • 13,406
  • 2
  • 25
  • 41