1

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!

1
  • global at global scope is meaningless (same as pass). I suggest you remove it. Commented Sep 14, 2014 at 22:43

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.