Geetansh G
Geetansh G

Reputation: 17

Decide which button has been pressed

I have the following code for creating a group of questions, however, I have run into an obstacle. I need a way to distinguish which button has been pressed, however, I'm unable to do so as all buttons are generated in a for loop:

tk.Label(self.canvas, text='Please choose an option below:').pack(fill='both',expand=True)
self.buttonGroup = tk.LabelFrame(self.canvas, text="Options")
self.buttonGroup.pack(fill='both',expand=True)
self.buttons = []

for i in range(0, len(options)):
    temp = tk.Button(self.buttonGroup, text=str(options[i]), bg=str(back), fg=str(fore))
    temp.pack(fill='both',expand=True)
    self.buttons.append(temp)

I have already read this article and tried the following code:

temp = tk.Button(self.buttonGroup, text=str(options[i]), bg=str(back), fg=str(fore), command=lambda: self.setSelection(i))

However, the function just sets the selected button to the index of the last button that was set.

How can I solve this problem? Please help.

Upvotes: 0

Views: 58

Answers (1)

Seaworn
Seaworn

Reputation: 557

Try passing the index as a default parameter in your lambda so that it is bound when the lambda is created, like this:

command=lambda i=i: self.setSelection(i)

Upvotes: 1

Related Questions