Search code examples
validationcheckboxtkinterbind

Tkinter checkbutton bind does not take the updated value


I have defined two checkbutton labels: (var is the class I use so that I have access to the variables outside as well)

lby = ttk.Checkbutton(var.frame,text="y-direction",variable=var.vel_y)
lbz = ttk.Checkbutton(var.frame,text="z-direction",variable=var.vel_z)
lby.grid(column=1,row=3,sticky=W)
lbz.grid(column=1,row=4,sticky=W)

Now, I bind the user-click on any of the buttons to call a function options_yz().

 def options_yz(key):
    print("y"+str(var.vel_y.get()))
    print("z"+str(var.vel_z.get()))
 lby.bind('<Button-1>', options_yz)
 lbz.bind('<Button-1>', options_yz)

But it seems to me that the button-click calls the function before changing the value of the variable. Is there any way to call the function after changing the variable?

For example: The default values for var.vel_y and var.vel_z are 0. I click on the checkbutton for y-direction. My output is:

y0
z0

My actual output should be:

y1
z0

Next I click on the checkbutton for z-direction. My output is:

y1
z0

My actual output should be:

y1
z1

Solution

  • As suggested by acw1668, instead of binding the function to user-click on the buttons, I bind it to the user-change of the variables. So my code is changed to:

    def options_yz(*args):
        print("y"+str(var.vel_y.get()))
        print("z"+str(var.vel_z.get()))
    var.vel_y.trace("w", options_yz)
    var.vel_z.trace("w", options_yz)
    

    And it does exactly what I need!