3

I tried to use the checkbutton widget along with a boolean variable. When I used a script without a class - it worked, but when I wrote the application as a class, it did not. Here's my code:

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() 

The checkbutton problem

In the picture you can see terminal with the output of the program. In the case in the picture the app was started and every combination of toggling the check button and pressing test button gave no results.

I tried to linked the variable in the constructor, then after the button was constructed, and both - with no results.

2
  • you can't use a normal variable as the value of the variable option. You have to use one of the special tkinter variables (StringVar, BooleanVar, etc). Jan 6, 2017 at 1:37
  • Thanks. I've read the answer below (1), and it works like a charm!
    – khaz
    Jan 6, 2017 at 13:07

1 Answer 1

5

Use BooleanVar. To obtain the states uses {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() 

enter image description here

2
  • Thanks a lot eyllanesc! You posted so precise answer and exact solution, with changes that were necessary -- it worked! Best regards :)
    – khaz
    Jan 6, 2017 at 13:09
  • @khaz If my answer helped you, you could mark it as correct.
    – eyllanesc
    Jan 6, 2017 at 13:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.