Python,Tkinter,Checkbutton:有没有办法检查开/关值

Cri*_*spy 0 python checkbox if-statement tkinter

我想要做的是设置if语句来检查一个checkbuttons值是打开还是关闭

我在想的是这样的

from Tkinter import *

def checkbutton_value():
    #If statement here
    #is their something like 

    #if checkbox_1.onvalue == True:
    #   checkbox_2.deselect()

    #if checkbox_1.varible == checkbox_1.onvalue:
    #   checkbox_2.deselect()

    print 'Need Help on lines 7-8 or 10-11'

root=Tk()

checkbox_1 = Checkbutton(root, text='1   ', command=checkbutton_value).pack()
checkbox_2 = Checkbutton(root, text='2   ', command=checkbutton_value).pack()

checkbox_3 = Checkbutton(root, text='QUIT', command=quit).pack()

root.mainloop()
Run Code Online (Sandbox Code Playgroud)

mgi*_*son 7

首先,不要在一行上创建和打包小部件. pack返回None,所以在上面的代码中,checkbox_1None.代替:

checkbox_1 = Checkbutton(root, text='1   ', command=checkbutton_value)
checkbox_1.pack()
Run Code Online (Sandbox Code Playgroud)

现在,要获取checkbutton的值:

def checkbutton_value1():
    if(var1.get()):
       var2.set(0)

def checkbutton_value2():
    if(var2.get()):
       var1.set(0)

var1=IntVar()
checkbox_1 = Checkbutton(root, text='1   ', variable=var1, command=checkbutton_value1)
checkbox_1.pack()
var2=IntVar()
checkbox_2 = Checkbutton(root, text='2   ', variable=var2, command=checkbutton_value2)
checkbox_2.pack()
Run Code Online (Sandbox Code Playgroud)

通常需要为这样的事情创建自己的checkbutton类:

class MyCheckButton(CheckButton):
    def __init__(self,*args,**kwargs):
        self.var=kwargs.get('variable',IntVar())
        kwargs['variable']=self.var
        Checkbutton.__init__(self,*args,**kwargs)

    def is_checked(self):
        return self.var.get()
Run Code Online (Sandbox Code Playgroud)