-1

I'm new to Tkinter, and I'd like the Checkbutton to print a string when it is checked, and a string when it is unchecked. However, self.value always returns PY_VAR0 whether the box is ticked or not.

from tkinter import *

class New:
    def __init__(self, master):
        value = StringVar()
        self.value = value
        frame = Frame(master)

        self.c = Checkbutton(
            master, text="Expand", variable=value,onvalue="Yes",
            offvalue="No",command=self.test)
        self.c.pack(side=LEFT)

    def test(self):
        if self.value == "Yes":
            print("Yes!")
        if self.value == "No":
            print("Not!")
        else:
            print(self.value)

root = Tk()
app = New(root)

root.mainloop()
Zach Timms
  • 11
  • 1
  • 5

1 Answers1

1

Try using

if self.value.get() == "Yes":

instead of

if self.value == "Yes":

Same everywhere you are trying to access the value of the checkbutton.

Also, it would be better to use

    if self.value.get() == "Yes":
        print("Yes!")
    else:
        if self.value.get() == "No":
            print("Not!")
        else:
            print(self.value.get())

since using your version will print the value twice if it is "Yes".

Adalee
  • 528
  • 12
  • 26
  • I think it would be easier if the if/else(if/else) statement were just an if/elif/else statement: `if self.value.get()=="Yes": print("Yes!)"; elif self.value.get()=="No": print("Not!"); else: print(self.value.get())` – elkshadow5 Jun 23 '20 at 00:44