0

what i am trying to do is setup if statements to check if a checkbuttons value is on or off

what i was thinking was something like this

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()

1 Answer 1

8

First, do not create and pack a widget on one line. pack returns None, so in your code above, checkbox_1 is None. Instead:

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

Now, to get the value of the 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()

It is often desireable to create your own checkbutton class for things like this:

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()
Sign up to request clarification or add additional context in comments.

4 Comments

Deleted my answer in lieu of your more detailed one. +1
Thanks i didnt no about the pack being None although i dont ever use pack/grid on the same line in real code but i guess there still is an effect in test code
@Crispy -- Also have a look at the Radiobutton widget ( effbot.org/tkinterbook/radiobutton.htm ). That might be more suited for what you want then a series of checkbuttons.
Wow, wonderful. The if statement has to be called inside the function called by command.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.