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

后端 未结 4 858
天涯浪人
天涯浪人 2020-12-10 14:43

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

from Tkinter import *

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


        
相关标签:
4条回答
  • 2020-12-10 15:05
    var4 = IntVar(value=1)
        Checkbutton(root, text="New", variable=var4, bg="light green").grid(row=12, column=0)
    

    This code will check all the boxes when you run the program.

    0 讨论(0)
  • 2020-12-10 15:15

    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)
    
    0 讨论(0)
  • 2020-12-10 15:20

    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.

    0 讨论(0)
  • 2020-12-10 15:25

    Just adding onto GunnerStone's answer - Because I was looking for something where I can reset my values/checkboxes.

    If you'd like to de-select the checkbox value for whatever reason, use deselect():

    from Tkinter import *
    
    CheckVar = IntVar()
    self.checkbutton = Checkbutton(self.root, text = "Test", variable = CheckVar)
    self.checkbutton.deselect()
    

    or use toggle to switch between the two:

    self.checkbutton.toggle()

    0 讨论(0)
提交回复
热议问题