问题描述
我有这段代码可以创建一个简单的复选框:
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)
就在 CheckVar 之后,但它不起作用.
right after CheckVar but it didn't work.
感谢您的帮助
这是我的完整代码.当我运行它时,该框仍未选中
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()
推荐答案
你的 CheckVar
是一个局部变量.它正在收集垃圾.将其另存为对象属性.此外,您可以一步创建变量并对其进行初始化:
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)
您也可以使用复选按钮的select
功能:
You can also use the select
function of the checkbutton:
self.checkbutton.select()
这篇关于Tkinter:有没有办法默认选中复选框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!