检查Python Tkinter中的复选框状态
你好,我正在尝试写一段Python代码,这段代码会根据选中了多少个复选框来在标签上显示一个值。为什么我的代码不工作呢?
var1=IntVar()
var2=IntVar()
var3=IntVar()
inlabel = StringVar()
label = Label (the_window, height = 1,bg = "white",width = 30, textvariable = inlabel,font = ("arial",50,"normal")).pack()
def check():
if(var1 == 0 and var2 == 0 and var3==1):
inlabel.set("odd")
if(var1 == 0 and var2 == 1 and var3==1):
inlabel.set("even")
if(var1 == 1 and var2 == 1 and var3==1):
inlabel.set("odd")
if(var1 == 0 and var2 == 1 and var3==0):
inlabel.set("odd")
if(var1 == 1 and var2 == 1 and var3==0):
inlabel.set("even")
if(var1 == 0 and var2 == 0 and var3==0):
inlabel.set("null")
if(var1 == 1 and var2 == 0 and var3==0):
inlabel.set("odd")
if(var1 == 1 and var2 == 0 and var3==1):
inlabel.set("even")
check1 = Checkbutton(the_window, text= "Gamma",variable=var1,command=check)
check2 = Checkbutton(the_window, text= "Beta",variable=var2,command=check)
check3 = Checkbutton(the_window, text= "Alpha",variable=var3,command=check)
check1.pack(side=RIGHT)
check2.pack()
check3.pack(side=LEFT)
谢谢 :)
2 个回答
2
你需要使用 get
并把它赋值给另一个变量,而不是 var1
。所以像这样做应该可以。
value1 = var1.get()
value2 = var2.get()
value3 = var3.get()
我假设你在你的实际程序中定义了你的父窗口 (the_window
)。
2
你需要使用 var.get()。下面是一个在 Python 3.3 中可以运行的例子。
from tkinter import *
root=Tk()
class CheckB():
def __init__(self, master, text):
self.var = IntVar()
self.text=text
c = Checkbutton(
master, text=text,
variable=self.var,
command=self.check)
c.pack()
def check(self):
print (self.text, "is", self.var.get())
check1 = CheckB(root, text="Gamma")
check2 = CheckB(root, text="Beta")
check3 = CheckB(root, text="Alpha")
希望这对你有帮助!- Ed