首页 > 解决方案 > 如果用户单击复选按钮,如何启用按钮

问题描述

这是我的代码

def register_user():

        Button(win, text="Sign Up", command=register_file, state=DISABLED).place(x=20, y=290) 
        var = IntVar()
        Checkbutton(win, variable=var,).place(x=15, y=249)

我怎样才能做到这一点

标签: pythonpython-3.xtkintertkinter.checkbutton

解决方案


这很简单,您可以使用command选项Checkbutton来在每次选择或取消选择复选框时触发 func,例如:

def register_user():
        def enable(*args):
            if var.get(): #if the checkbutton is tick
                b['state'] = 'normal' #enable the button
            else: #else
                b['state'] = 'disabled' #disable it

        but = Button(win, text="Sign Up", command=register_file, state=DISABLED)
        but.place(x=20, y=290) 
        var = IntVar()
        cb = Checkbutton(win, variable=var,command=enable) #command option triggers the enable
        cb.place(x=15, y=249)

为什么我说分配变量并place()在另一行?这样小部件就不会变成None.

Entry 对象和所有其他小部件的 grid、pack 和 place 函数返回 None。在 python 中,当您执行 a().b() 时,表达式的结果是 b() 返回的任何内容,因此 Entry(...).grid(...) 将返回 None。

为了更好地理解它的来源,请阅读这里


推荐阅读