Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tkinter: is there a way to check checkboxes by default?

I have this piece of code that will create a simple checkbox :

from Tkinter import *

CheckVar = IntVar()
self.checkbutton = Checkbutton(self.root, text = "Test", variable = CheckVar)

However this checkbox in unchecked by default and I'm searching for a way to check it.

So far I have tried to insert

CheckVar.set(1)

right after CheckVar but it didn't work.

Thanks for your help

Edit : here is my full piece of code. When I run it, the box is still unchecked

from Tkinter import *

class App():
    def __init__(self, root):   
        self.root = root
        CheckVar = IntVar()
        CheckVar.set(1)
        self.checkbutton = Checkbutton(self.root, text = "Test", variable = CheckVar)
        self.checkbutton.grid(row=0, column=0,)


root = Tk()
app = App(root)
root.mainloop()
like image 872
Marvin Lerousseau Avatar asked Jun 02 '16 14:06

Marvin Lerousseau


People also ask

How do I find the value of my Checkbutton?

IntVar(). get() returns the onvalue or ofvalue of the Checkbutton, based on the status. You can either assign a function to command option of Checkbutton, and read the status of Checkbutton as and when the button is checked or not.

How do I make a check box in Python?

Checkbutton(text, variable) to create a checkbox; the variable is a tk. StringVar() . Use command argument to specify a function that executes when the button is checked or unchecked. Use the onvalue and offvalue to determine what value the variable will take.

What is IntVar () in tkinter?

Tkinter IntVar() FunctionA variable defined using IntVar() function holds integer data where we can set integer data and can retrieve it as well using getter and setter methods.


2 Answers

Your CheckVar is a local variable. It's getting garbage collected. Save it as an object attribute. Also, you can create the variable and initialize it all in one step:

self.CheckVar = IntVar(value=1)
self.checkbutton = Checkbutton(..., variable = self.CheckVar)

You can also use the select function of the checkbutton:

self.checkbutton.select()
like image 171
Bryan Oakley Avatar answered Oct 19 '22 03:10

Bryan Oakley


I think the function you are looking for is .select()

This function selects the checkbutton (as can be assumed from the function name)

Try calling this function after your widget is defined:

from Tkinter import *

CheckVar = IntVar()
self.checkbutton = Checkbutton(self.root, text = "Test", variable = CheckVar)
self.checkbutton.select()

By calling the function right after the widget is created, it looks as though it's selected by default.

like image 22
Gunner Stone Avatar answered Oct 19 '22 03:10

Gunner Stone