Question

I have a two very simple check buttons, whose variables I am saving within a list (varss), and one button. But I do not understand why when I call var_states (by pressing the button), I cannot get the off/on values. Any help is appreciated. Thanks!

from Tkinter import *

def run():
    # create the root and the canvas
    root = Tk()
    canvas = Canvas(root, width=300, height=200)
    canvas.pack()
    class Struct: pass
    canvas.data = Struct()
    # canvas.data.givenIngredients = set()

    prefInput(canvas)
    # and launch the app
    root.mainloop()

def var_states(varss):
    for var in varss:
        var.get()

def prefInput(canvas):
    master = Tk()
    var1, var2 = IntVar(), IntVar()
    Checkbutton(master, text="male", variable=var1).grid(row=1, sticky=W)
    varss = [var1, var2]
    Checkbutton(master, text="female", variable=var2).grid(row=2, sticky=W)
    Button(master, text='Show', command=lambda:var_states(varss)).grid(row=4, sticky=W, pady=4)

run()
Was it helpful?

Solution

You have created two Tcl interpreters, one with each call to Tk(). Each Tcl interpreter has variables distinct from every other Tcl interpreter.

The first interpreter created becomes the default interpreter for a Tkinter object which does not explicitly relate itself to an existing interpreter (for instance, by passing a widget in that interpreter to its 'master' in its constructor)

You probably did not intend to create two interpreters, so for starters don't execute

master = Tk()

in prefInput. Instead, use the canvas argument as the first argument to your Checkbutton calls (replacing master), and also use it in the calls to IntVar: var1, var2 = IntVar(canvas), IntVar(canvas). (if you do want an additional window within your application, use Tkinter.Toplevel instead of Tkinter.Tk for the second window)

Finally, for testing I changed your Var_states function so that it printed more information:

def var_states(varss):
    print "var_states", varss
    for var in varss:
        print var, var.get()

The final program then reads:

from Tkinter import *

def run():
    # create the root and the canvas
    root = Tk()
    canvas = Canvas(root, width=300, height=200)
    canvas.pack()
    class Struct: pass
    canvas.data = Struct()
    # canvas.data.givenIngredients = set()

    prefInput(canvas)
    # and launch the app
    root.mainloop()

def var_states(varss):
    print "var_states", varss
    for var in varss:
        print var, var.get()

def prefInput(canvas):
    var1, var2 = IntVar(canvas), IntVar(canvas)
    Checkbutton(canvas, text="male", variable=var1).grid(row=1, sticky=W)
    varss = [var1, var2]
    Checkbutton(canvas, text="female", variable=var2).grid(row=2, sticky=W)
    Button(canvas, text='Show', command=lambda:var_states(varss)).grid(row=4, sticky=W, pady=4)

run()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top