Mar*_*eau 7 python checkbox tkinter
我有这段代码将创建一个简单的复选框:
from Tkinter import *
CheckVar = IntVar()
self.checkbutton = Checkbutton(self.root, text = "Test", variable = CheckVar)
Run Code Online (Sandbox Code Playgroud)
但是,默认情况下取消选中此复选框,我正在搜索检查它的方法.
到目前为止,我试图插入
CheckVar.set(1)
Run Code Online (Sandbox Code Playgroud)
就在CheckVar之后但它没有用.
谢谢你的帮助
编辑:这是我的完整代码.当我运行它时,该框仍未选中
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()
Run Code Online (Sandbox Code Playgroud)
Bry*_*ley 13
你CheckVar是一个局部变量.它正在收集垃圾.将其另存为对象属性.此外,您可以创建变量并在一个步骤中初始化它:
self.CheckVar = IntVar(value=1)
self.checkbutton = Checkbutton(..., variable = self.CheckVar)
Run Code Online (Sandbox Code Playgroud)
Gun*_*one 10
我认为你正在寻找的功能是 .select()
此函数选择复选按钮(可以从函数名称中假设)
在定义小部件后尝试调用此函数:
from Tkinter import *
CheckVar = IntVar()
self.checkbutton = Checkbutton(self.root, text = "Test", variable = CheckVar)
self.checkbutton.select()
Run Code Online (Sandbox Code Playgroud)
通过在创建窗口小部件后立即调用该函数,它看起来好像是默认选中的.
只是添加到 GunnerStone 的答案 - 因为我正在寻找可以重置我的值/复选框的东西。
如果您出于某种原因想要de-select该复选框值,请使用deselect():
from Tkinter import *
CheckVar = IntVar()
self.checkbutton = Checkbutton(self.root, text = "Test", variable = CheckVar)
self.checkbutton.deselect()
Run Code Online (Sandbox Code Playgroud)
或使用toggle在两者之间切换:
self.checkbutton.toggle()