I'm trying taking to make a GUI application using Python and tkinter. In this example I want the user to select multiple different fruits, and this should then set that fruit's value in a dictionary to True.
However, I'm using a for loop to generate the checkbuttons, and whenever I run, the program just sets the last fruit (Mango) to True, regardless of which button was checked. The code is as follows:
import tkinter as tk
def true_in_dict(fruit):
dict_fruits[fruit] = True
print(dict_fruits)
window = tk.Tk()
lbl_fruits = tk.Label(master=window, text="Select fruits:")
lbl_fruits.grid(row=0, sticky="w")
frm_fruits = tk.Frame(master=window)
frm_fruits.grid(row=1, column=0)
dict_fruits = {"Apple": False,
"Orange": False,
"Pear": False,
"Banana": False,
"Mango": False}
for i, k in enumerate(dict_fruits):
chkVal = tk.BooleanVar()
chkVal.set(False)
chk_fruit = tk.Checkbutton(master=frm_fruits, text=k, variable=chkVal, command=lambda: true_in_dict(k))
chk_fruit.grid(row=i, column=0,sticky="w")
window.mainloop()
Do I need to make a dictionary of checkbuttons to get round this? Or is there a better way?