Tkinter 上的复选按钮值未更改

Checkbutton values on Tkinter not changing

我是 Tkinter 的新手,我希望 Checkbutton 在选中时打印一个字符串,在未选中时打印一个字符串。但是,self.value 总是 returns PY_VAR0 无论该框是否被勾选。

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()

尝试使用

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

而不是

if self.value == "Yes":

在任何你试图访问复选按钮值的地方都是一样的。

还有,最好用

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

因为如果它是 "Yes",使用您的版本将打印两次该值。