Python tkinter Checkbutton防止切换

2024-10-02 02:24:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个tkinter GUI,其中有两个复选按钮。它们代表“或”和“和”。选中“或”按钮时,变量andCond为False;选中“和”按钮时,变量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()

这是所有工作需要,除了有一件小事,我无法修复。选中或按钮时,如果我再次单击它,则不会发生任何事情(这正是我想要的) 但是,当“和”按钮被选中,我再次单击它时,按钮将切换,或者现在被选中

我怎样才能防止这种情况

多谢各位

R


Tags: orimporttruegettkinterchecknotroot
2条回答

导致这种行为的只是一个小错误:

# 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按钮时会不断切换

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

但是,如果您正在创建一个独占选项(即:用户只能选择“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

相关问题 更多 >

    热门问题