Reputation: 17
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
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