rmore911
rmore911

Reputation: 215

Python tkinter Checkbutton prevent toggling

I have a tkinter GUI that has two CheckButtons in it. They are for 'OR' and 'AND'. When the OR button is checked, the variable andCond is False, and when AND button is checked, the variable andCond is True.

from Tkinter import *
import pdb
import tkinter as tk

global andCond

root = tk.Tk()
color = '#aeb3b0'

def check():
    global andCond
    if checkVar.get():
        print('OR')
        andCond = not(checkVar.get())
        print(andCond)
    else:
        print('AND')
        andCond = not(checkVar.get())
        print(andCond)

checkVar = tk.IntVar()
checkVar.set(True)
    
checkBoxAND = tk.Checkbutton(root, text = "AND", variable = checkVar, onvalue = 0, offvalue = 1, command = check, width =19, bg = '#aeb3b0')
checkBoxAND.place(relx = 0.22, rely = 0.46)

checkBoxOR = tk.Checkbutton(root, text = "OR", variable = checkVar, onvalue = 1, offvalue = 1, command = check, width =19, bg = '#aeb3b0')
checkBoxOR.place(relx = 0.22, rely = 0.36)

andCond = not(checkVar.get())
print(andCond)

root.mainloop()

This is all working as needed, except there is one small thing that I am unable to fix. When the OR button is checked, if i click on it again, nothing happens (which is what I want) But when the AND button is checked, and i click on it again, the button toggles and OR is now checked.

How can I prevent this?

Thank you

R

Upvotes: 0

Views: 791

Answers (2)

Bryan Oakley
Bryan Oakley

Reputation: 385880

A checkbutton should have a unique variable associated with it. You're using the same variable for both checkbuttons. If you want them user to select each button independent of the other (ie: you can check both "AND" and "OR"), they need to have separate values.

However, if you're creating an exclusive choice (ie: the user can only pick one of "AND" or "OR") then checkbuttons are the wrong widget. The radiobutton widget is designed to make an exclusive choice, and they do so by sharing a common variable.

choiceAND = tk.Radiobutton(root, text = "AND", variable = checkVar, value=0, command = check, width =19, bg = '#aeb3b0')
choiceOR = tk.Radiobutton(root, text = "OR", variable = checkVar, value=1, command = check, width =19, bg = '#aeb3b0')

With that, the user can choose only one, and the value of the associated variable will either be 1 or 0.

Upvotes: 1

Moosa Saadat
Moosa Saadat

Reputation: 1167

There's just a small mistake which is causing this behavior:

# Set both onvalue and offvalue equal to 0
checkBoxAND = tk.Checkbutton(root, text = "AND", variable = checkVar, onvalue = 0, offvalue = 0, command = check, width =19, bg = '#aeb3b0')

You are setting offvalue equal to 1 which creates the problem because the value of checkVar keeps toggling on pressing the AND button.

Upvotes: 0

Related Questions