1

I'm just doing my first steps in tkinter and I'm stuck trying to figure out why this code is not working:

from tkinter import *
from tkinter import ttk

root = Tk()
spam = StringVar()
checkbutton = ttk.Checkbutton(
    root, text="SPAM?", variable=spam, onvalue="Yes, SPAM!", offvalue="Boo, SPAM!")
checkbutton.pack()
print(spam.get())

root.mainloop()

The variable spam is empty, no matter if my checkbutton is checked or unchecked. Looking at the examples and documentation was a dead end too. Why is my variable still empty?

1
  • 1
    You are printing the value about a millisecond after you create the widget. The user will not even have seen the UI yet, much less interact with it. Commented Feb 10, 2018 at 1:38

1 Answer 1

1

Replace:

print(spam.get())

with:

checkbutton['command'] = lambda arg=spam: print(arg.get())

In order to see that the variable indeed does store the values.


The problem is when your print is called spam.get() equals "" as:

spam = StringVar()

is identical to:

spam = StringVar(value="")

The checkbutton is initially on a default neither-on, nor-off state(as spam is neither the off nor the on value), but it's hard to notice for the version(if at all), replace:

checkbutton = ttk.Checkbutton(...

with:

checkbutton = Checkbutton(...

to use the default Checkbutton from , it is much more distinctively displayed.

Also further note that the Checkbutton requires being used in order to call spam.set(checkbutton['onvalue']) or spam.set(checkbutton['offvalue']).

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your kind help! That was exactly the problem.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.