1

In this code I'm trying to use these two checkbuttons, that should be active/inactive, completely independent of one another, but it doesn't work as expected:

from tkinter import * 

root = Tk()

enable = {'jack': 0, 'john': 0}

def actright(x):
    print(enable.get(x))

for machine in enable:
    l = Checkbutton(root, text=machine, variable=enable[machine], onvalue=1, offvalue=0,
                    command = lambda: actright(machine))
    l.pack(anchor = W)

root.mainloop()

When either "jack" or "john" is checked, they both activate/deactivate at the same time. I assume this is because they are initiated at the same value, but is there a way for them to be independent, but also still both be initiated at "0"?

Aside from my main question I do have a sub topic: Regardless of how many times the buttons are checked they still return "0", However the "onvalue" is set to 1 for the checkbutton, so shouldn't they alternate between returning 1 and 0 instead?

2 Answers 2

2

You need a dictionary with IntVars (or even the checkButtons) in it. Then you need the usual lambda machine=machine (classic gotcha when initializing widgets in a loop). So the result will be something like that:

from tkinter import * 

root = Tk()

enable = {'jack': 0, 'john': 0}
checkvalues = {}

def actright(x):
    print(x,  checkvalues[x].get())

for machine in enable:
    myvar = IntVar()
    myvar.set(enable[machine])
    checkvalues[machine] =myvar
    l = Checkbutton(root, text=machine, onvalue=1, offvalue=0, variable = myvar, 
                    command = lambda machine=machine: actright(machine))
    l.pack(anchor = W)

root.mainloop()
Sign up to request clarification or add additional context in comments.

1 Comment

I think you answered my question exactly, thanks for the help!
0

Adding to Eric Levieil's excellent answer; if you'd like to print the binary only, be sure to define actright() without printing x, or you will end up printing the name in the dictionary associated with the value.

def actright(x):
    print(checkvalues[x].get())

(Note: not enough reputation to comment yet)

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.