0

I'd like to print the current value of the checkbox variable. Instead I get the last before the click. what am I doing wrong?

import tkinter as tk

def widget(frame):
    chbx_value = 0
    widget_col_span = 1

    # widgets checkbox
    var_c = tk.IntVar(master=frame, value=chbx_value)
    widget_c = tk.Checkbutton(master=frame, text='', variable=var_c)
    widget_c.bind("<ButtonRelease>", lambda event: print(var_c.get()))
    widget_c.grid(row=0, column=0, columnspan=widget_col_span, padx=1, pady=1, sticky="ns")

root = tk.Tk()
root.title('My Window')
widget(root)
root.mainloop()

1 Answer 1

1

The event <ButtonRelease> obviously occurs before your variable has changed. My advice would be to use the command kwarg in the Checkbutton constructor. Besides, it probably makes more sense to use a boolean as variable:

import tkinter as tk

def widget(frame):
    widget_col_span = 1

    # widgets checkbox
    var_c = tk.BooleanVar(master=frame)
    widget_c = tk.Checkbutton(master=frame, text='', variable=var_c, command=lambda: print(var_c.get()))
    widget_c.grid(row=0, column=0, columnspan=widget_col_span, padx=1, pady=1, sticky="ns")

root = tk.Tk()
root.title('My Window')
widget(root)
root.mainloop()
Sign up to request clarification or add additional context in comments.

2 Comments

any way to make it occur after the variable changes using my approach?
I don't really see how... it would probably be much more convoluted to achieve the same result. Another solution would be to trace your variable instead: var_c.trace("w", lambda *args : print(var_c.get()))

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.