-1

So, I was learning about checkbuttons in Tkinter and I am stuck with this wierd issue. This is the code that I am using

root = Tk()
def showValue():
    print(val.get())
    Label(text=str(val.get())).pack()
val = StringVar()
Checkbutton(root, text="Check me!", variable=val, onvalue="on", offvalue="off").pack()
Button(text="Click",command=showValue).pack()
root.mainloop()

Firstly, the box is checked by default, which I think is because the offvalue is set to something i.e not False (i.e not 0 or an empty string), please correct me if I am wrong. But, the weird thing that I notice here is that when I hit the button, which should ideally show me a Label with text="on", but actually it doesn't until I deselect the box manually, after which the button behaves normally. I know I couldn't explain whats happening here properly, but if you try it out yourself you would see it. Here's an image of the GUI.
enter image description here
Now, the two blank lines that you see after the button is actually because I clicked the button twice before doing anything with the checkbox, and once I deselected the checkbox and then clicked the button, it displayed off. Can someone please what's actually happening here? Thanks in advance!

  • Set an initial value by `StringVar(value="off")` instead? – Henry Yik May 13 '20 at 16:01
  • Does this answer your question? [Tkinter: is there a way to check checkboxes by default?](https://stackoverflow.com/questions/37595078/tkinter-is-there-a-way-to-check-checkboxes-by-default) – stovfl May 13 '20 at 17:18
  • @stovfl Actually I know how to fix this, by deselecting the checkbox, but I wanted to know why is this happening? –  May 13 '20 at 19:39
  • ***wanted to know why is this happening?***: Your `var` is neither `onvalue="on"` nor `offvalue="off"` therefore the `Checkbox` is in **undefined** state. Read [The Tkinter Checkbutton Widget](http://effbot.org/tkinterbook/checkbutton.htm) – stovfl May 13 '20 at 20:07

1 Answers1

0

You just have to use StringVar(value="off"). Also doing this Label(text=str(val.get())).pack() will cause memory leak but rather you have to use config to position your result at same position Label.config(text=val.get()). I have refactored the code to look more readable.

from tkinter import *


def showValue():
    Label.config(text=val.get())


root = Tk()


val = StringVar(value="off")
check = Checkbutton(root, text="Check me!", variable=val, onvalue="on", offvalue="off")
check.pack()

btn = Button(text="Click",command=showValue)
btn.pack()

lbl = Label(root)
lbl.pack()


root.mainloop()
Som Shekhar Mukherjee
  • 4,701
  • 1
  • 12
  • 28
AD WAN
  • 1,414
  • 2
  • 15
  • 28
  • Once we are using StringVar(value="off"), we don't need if else in the function "showValue" because the "if" condition in this case never gets executed. Just "def showValue(): Label.config(text=val.get())" would be sufficient. –  May 13 '20 at 19:52