Reputation: 23
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?
Upvotes: 1
Views: 218
Reputation: 808
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)
Upvotes: 0
Reputation: 3574
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()
Upvotes: 2