I am running a loop which adds Tkinter
buttons to a list. I want to make each button have a command that runs based on the particular button that was clicked - for now - toggling the relief between raised
and sunken
.
I can't get the command to run on the specific button, it always runs on the last button in the list of buttons, regardless of which button I actually click on.
I tried manually setting the command for each button without a loop (but still with a list!), which worked, but I need to use a loop.
I also tried creating a second loop after the first one.
def toggle_button(self):
if self['relief'] == 'raised':
self['relief'] = 'sunken'
elif self['relief'] == 'sunken':
self['relief'] = 'raised'
for event in list_of_data:
event_buttons.append(Button(popup, text=event['event name'], relief='raised'))
event_buttons[-1].pack()
# Approach 1
event_buttons[-1].config(command=lambda: toggle_button(event_buttons[-1]))
Approach 2:
for button in event_buttons:
button.config(command=lambda: toggle_button(button))
I expect event_buttons[0]['command']
to be
lambda: toggle_button(event_buttons[0])
event_buttons[1]['command'] = lambda: toggle_button(event_buttons[1])
event_buttons[2]['command'] = lambda: toggle_button(event_buttons[2])
And so on.