【问题标题】:Python, Tkinter, Checkbutton: Is there a way to check on/off valuePython,Tkinter,Checkbutton:有没有办法检查开/关值
【发布时间】:2012-07-09 21:49:10
【问题描述】:

我要做的是设置 if 语句来检查 checkbuttons 值是打开还是关闭

我的想法是这样的

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

【问题讨论】:

    标签: python if-statement tkinter checkbox


    【解决方案1】:

    首先,不要在一行中创建和打包小部件pack 返回None,所以在上面的代码中,checkbox_1None。而是:

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

    现在,获取检查按钮的值:

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

    通常希望为这样的事情创建自己的检查按钮类:

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

    【讨论】:

    • 删除了我的答案,而不是您更详细的答案。 +1
    • 谢谢我不知道包是 None 虽然我从来没有在实际代码的同一行上使用包/网格,但我想在测试代码中仍然有影响
    • @Crispy -- 还可以查看 Radiobutton 小部件 (effbot.org/tkinterbook/radiobutton.htm)。这可能比一系列复选按钮更适合您想要的。
    • 哇,太棒了。 if 语句必须在命令调用的函数内部调用。
    猜你喜欢
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    • 2015-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多