检查按钮状态检查Python Tkinter

时间:2014-05-04 05:52:03

标签: 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 个答案:

答案 0 :(得分:2)

您需要使用get并将其分配给另一个变量而不是var1。 所以这样的事情应该有效。

value1 = var1.get()
value2 = var2.get()
value3 = var3.get()

我假设您在实际程序中定义了父窗口(the_window)。

答案 1 :(得分:2)

您需要使用var.get()。这是Python3.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")

希望有所帮助! - 艾德