Tkinter:默认情况下,有没有一种方法可以选中复选框? [英] Tkinter: is there a way to check checkboxes by default?
本文介绍了Tkinter:默认情况下,有没有一种方法可以选中复选框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这段代码将创建一个简单的复选框:
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)
这篇关于Tkinter:默认情况下,有没有一种方法可以选中复选框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文