【问题标题】:Python tkinter Checkbutton prevent togglingPython tkinter Checkbutton 防止切换
【发布时间】:2020-10-20 00:43:06
【问题描述】:

我有一个 tkinter GUI,里面有两个 CheckButton。它们用于“或”和“与”。当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

【问题讨论】:

  • 您是否希望用户只选择“OR”或“AND”之一,而不是两者?如果是这种情况,则 Checkbutton 是不正确的小部件。单选按钮专为独家选择而设计。

标签: python tkinter toggle


【解决方案1】:

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

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

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。

【讨论】:

  • 谢谢。我以前从未使用过单选按钮。但根据您的描述,我认为这是适合我的方式。
【解决方案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 按钮时不断切换。

【讨论】:

    猜你喜欢
    • 2018-05-17
    • 1970-01-01
    • 2023-04-07
    • 1970-01-01
    • 1970-01-01
    • 2016-06-16
    • 2018-10-26
    • 1970-01-01
    • 2017-01-18
    相关资源
    最近更新 更多