如何将复选按钮与变量绑定

kha*_*haz 3 python tkinter

我尝试将检查按钮小部件与布尔变量一起使用。当我使用没有类的脚本时,它起作用了,但是当我将应用程序编写为类时,它不起作用。这是我的代码:

from tkinter import Tk, Frame, Checkbutton, Button

class MyFrame(Frame):   
    def __init__(self, parent):     
        Frame.__init__(self, parent)
        self.parent = parent

        self.test01 = False

        checkbutton = Checkbutton(parent, text='check it', variable=self.test01, command=self.testcheck)
        checkbutton.var = self.test01
        checkbutton.pack()

        testbutton = Button(parent, text='check test', command=self.testcheck)
        testbutton.pack()
        self.parent.title('Checkbutton test')


    def testcheck(self):

        print('Check test: ' + str(self.test01))

def main():

    root = Tk()
    app = MyFrame(root)
    root.mainloop() 

if __name__ == '__main__':
    main() 
Run Code Online (Sandbox Code Playgroud)

检查按钮问题

在图片中您可以看到带有程序输出的终端。在图片中的情况下,应用程序已启动,并且切换检查按钮和按测试按钮的每种组合都没有结果。

我尝试在构造函数中链接变量,然后在构造按钮后链接变量,两者都没有结果。

eyl*_*esc 5

使用BooleanVar。获得各州使用{variable}.get()

from tkinter import Tk, Frame, Checkbutton, Button, BooleanVar

class MyFrame(Frame):

    def __init__(self, parent):

        Frame.__init__(self, parent)
        self.parent = parent
        self.test01 = BooleanVar()
        checkbutton = Checkbutton(parent, text='check it',
        variable=self.test01, command=self.testcheck)

        checkbutton.pack()

        testbutton = Button(parent, text='check test', command=self.testcheck)
        testbutton.pack()
        self.parent.title('Checkbutton test')


    def testcheck(self):

        print('Check test: ' + str(self.test01.get()))

def main():

    root = Tk()
    app = MyFrame(root)
    root.mainloop() 

if __name__ == '__main__':
    main() 
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述