Python, Tkinter: Get Text from Checkbutton when Checked
Question: I'm working with the following code. My goal is to get the text of a
Checkbutton when it is checked, and append that text to a list. I want to
write the code dynamically, because the size of list 'x' may change. Here's
what I have so far:

    
    
    from Tkinter import *
    root = Tk()
    
    global j
    j = []
    
    x = ['hello', 'this', 'is', 'a', 'list']
    
    def chkbox_checked():
        j.append(c.cget("text"))
    
    for i in x:
    
        c = Checkbutton(root, text=i, command=chkbox_checked)
        c.grid(sticky=W)
    
    mainloop()
    
    print j
    

My output so far for j has been:

    
    
    ['list', 'list', 'list', 'list', 'list'] #depending on how many Checkbuttons I select
    

I'm looking for an output that is like this:

    
    
    ['this', 'list'] #depending on the Checkbuttons that I select; this would be the output if I
    #selected Checkbuttons "this" and "list".
    

I've experimented with the "variable" option in the Checkbutton, but I can't
seem to connect the dots. Can anyone point me in the right direction? I have a
feeling it's relatively straightforward. Thanks!


Answer: The problem is that the variable c in the for loop is reassigned every
iteration. That's why it only prints the last element `list`.

One solution is to use lambda functions.

    
    
    def chkbox_checked(text):
        return lambda : j.append(text)
    
    for i in x:
        c = Checkbutton(root, text=i, command=chkbox_checked(i))
        c.grid(sticky=W)
    

