Tkinter上的Checkbutton值不变

时间:2015-05-03 00:20:18

标签: python button tkinter

我是Tkinter的新手,我希望Checkbutton在检查时打印一个字符串,并在取消选中时输入一个字符串。但是,无论是否勾选方框,self.value始终都会返回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()

1 个答案:

答案 0 :(得分:1)

尝试使用

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

而不是

if self.value == "Yes":

在尝试访问checkbutton的值时,无处不在。

此外,最好使用

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

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

相关问题