Dominik Praski Dominik Praski - 5 days ago 4
Python Question

check box, when i tick the box the value of var does not change to 1

When I click on the check box I want the value of

var1
to change to 1. However, when I do
var1.get()
in a function the value always comes up as 0.

var1 = IntVar()
tickbox_1 = Checkbutton(custom, text=label_1, variable=var1,)
tickbox_1.grid(row=2,column=1)


I have a function that is called by a button which gets the value of
var1
and prints it.

def custom_create():
print(var1.get())


Is there anything I can do to make sure that
var1
becomes 1 when the box is ticked? Also, how can I get the box ticked when the window launches?

Answer

Your code is substantially correct, so the cause of your problem must be in other code you haven't shown us.

FWIW, here's a small working demo.

import tkinter as tk

root = tk.Tk()

var1 = tk.IntVar()
var1.set(1)

tickbox_1 = tk.Checkbutton(root, text='Tick_1', variable=var1)
tickbox_1.grid(row=0, column=0)

def callback():
    print(var1.get())

b = tk.Button(root, text="Show", command=callback)
b.grid(row=0, column=1)

root.mainloop()

The line var1.set(1) makes the Checkbox start out in the ticked state.

Comments