-1

Whatever I do to my checkbutton, it does not seem to set the variable. Here's the parts of the code that are involved:

class Window:
    def __init__(self):
        self.manualb = 0 #to set the default value to 0

    def setscreen(self):
        #screen and other buttons and stuff set here but thats all working fine
        manual = tkr.Checkbutton(master=self.root, variable=self.manualb, command=self.setMan, onvalue=0, offvalue=1) #tried with and without onvalue/offvalue, made no difference
        manual.grid(row=1, column=6)

    def setMan(self):
        print(self.manualb)
        #does some other unrelated stuff

It just keeps printing 0. Am I doing something wrong? Nothing else does anything to manual.

Coen Visser
  • 23
  • 1
  • 6

2 Answers2

6

You're looking for IntVar()

IntVar() has a method called get() which will hold the value of the widget you assign it to.

In this particular instance, it will be either 1 or 0 (On or off). You can use it something like this:

from tkinter import Button, Entry, Tk, Checkbutton, IntVar

class GUI:

    def __init__(self):

        self.root = Tk()

        # The variable that will hold the value of the checkbox's state
        self.value = IntVar()

        self.checkbutton = Checkbutton(self.root, variable=self.value, command=self.onClicked)
        self.checkbutton.pack()

    def onClicked(self):
        # calling IntVar.get() returns the state
        # of the widget it is associated with 
        print(self.value.get())

app = GUI()
app.root.mainloop()
Jebby
  • 1,845
  • 1
  • 12
  • 25
  • 1
    Hi @Jebby. It's typically a good idea to explain why someone should or shouldn't be doing/using something in their program. This makes it easier for newcomers to the ideas and languages you have described to understand the answer. – Ethan Field Nov 08 '17 at 11:50
  • 1
    Thanks @EthanField I have edited my post to include a little more information on what `IntVar` is. – Jebby Nov 08 '17 at 12:02
3

This is because you need to use one of tkinter's variable classes.

This would look something like the below:

from tkinter import *

root = Tk()

var = IntVar()

var.trace("w", lambda name, index, mode: print(var.get()))

Checkbutton(root, variable=var).pack()

root.mainloop()

Essentially IntVar() is a "container" (very loosely speaking) which "holds" the value of the widget it's assigned to.

Ethan Field
  • 4,646
  • 3
  • 22
  • 43