I have populated a Tkinter Frame with many Checkbuttons (around 100) using the keys from a Dictionary, so I used a for loop to do this. To save the state (0 or 1), I have another dictionary to take care of this. However, when I try to assign a command that will print the state when checked (i.e. clicked on), nothing happens. Here is my code to create the Checkbuttons:
import Tkinter as tk
items = {'Books': 5, 'Games': 20, 'Food': 10, 'Clothes': 2}
items_check = {}
class Application(tk.Frame):
def __init__(self, master):
self.master = master
tk.Frame.__init__(self, master, width=500, height=500)
self.master.title('Application')
self.pack_propagate(0)
self.pack()
global items
global items_check
self.row_var = 0
self.column_var = 0
self.row_count = 0
for key in items.iterkeys():
items_check[key] = tk.IntVar()
item_button = tk.Checkbutton(self, text=key, variable=items_check[key], command=self.check_item(key))
if self.row_count % 15 == 0:
self.row_count = 0
self.row_var = 0
self.column_var += 1
item_button.grid(row=self.row_var, column=self.column_var, sticky=tk.W)
self.row_var += 1
self.row_count += 1
def check_item(self, key):
global items_check
if items_check[key].get() == 1:
items_check[key].set(0)
print key
print items_check[key].get()
elif items_check[key].get() == 0:
items_check[key].set(1)
print key
print items_check[key].get()
app = Application(tk.Tk())
app.run()
Essentially when I click on any of the checkbuttons, I want to print that specific checkbutton's key and value to the console. Nothing happens with this code. Any ideas? Thanks!