Python Tkinter上的Checkbutton值未更改
我是Tkinter的新手,我希望Checkbutton在选中时打印一个字符串,在未选中时打印一个字符串。但是,Python Tkinter上的Checkbutton值未更改,python,button,tkinter,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 =
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()
试用
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())
由于使用您的版本会在值为“是”时打印两次。我认为如果if/else(if/else)语句只是if/elif/else语句会更容易:
if self.value.get()=“Yes”:打印(“Yes!”;elif self.value.get();其他:打印(self.value.get())