Python tkinter Checkbutton 防止切换

Python tkinter Checkbutton prevent toggling

我有一个 tkinter GUI,里面有两个 CheckButton。它们用于 'OR' 和 'AND'。选中OR按钮时,变量andCond为False,选中AND按钮时,变量andCond为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()

除了有一件小事我无法修复外,这一切都在按需进行。当 OR 按钮被选中时,如果我再次点击它,什么也不会发生(这就是我想要的) 但是当 AND 按钮被选中时,我再次点击它,按钮切换并且 OR 现在被选中。

我怎样才能避免这种情况?

谢谢

R

只有一个小错误导致了此行为:

# 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')

您将 offvalue 设置为 1,这会产生问题,因为 checkVar 的值在按下 AND 按钮时不断切换。

复选按钮应该有一个与之关联的唯一变量。您对两个复选按钮使用相同的变量。如果您希望用户 select 每个按钮相互独立(即:您可以同时选中“AND”和“OR”),则它们需要具有单独的值。

但是,如果您要创建排他性选择(即:用户只能选择“AND”或“OR”之一),则复选按钮是错误的小部件。 radiobutton 小部件旨在做出独占选择,它们通过共享一个公共变量来实现。

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

这样,用户只能选择一个,关联变量的值将是 1 或 0。