首页 > 解决方案 > 如何复选框以启用 Tkinter 中的按钮

问题描述

self.label_5 = tk.Checkbutton(self.master, text="I agree to the", bg='white', width=14,font=("Arial", 8), command= activator)
self.label_5.place(x=112, y=410)
self.button_2 = tk.Button(text='Proceed', width=20, bg='white', state = tk.DISABLED, bd=1, 
highlightbackground='black', font=("Arial", 10)).place(x=208, y = 512)

def activator(button):
    if (self.button_2 ['state'] == tk.DISABLED):
        self.button_2 ['state'] = tk.NORMAL
    else:
        self.button_2['state'] = tk.DISABLED

我想在检查复选按钮后启用继续按钮,但我似乎无法弄清楚。

标签: pythontkinter

解决方案


您必须对代码进行以下更改:

  • 将函数命名activator为 asself.activator时,必须将其引用为Button( button_2) command
  • 您必须将parameter名为button的函数的名称更改activatorself.
  • 您需要做的最重要的事情是将放置Button( button_2) 和Checkbutton( label_5) 的代码部分移到新行。就像我在下面的代码中所做的那样。这样做的原因是packgrid而且place总是如此return None。当您在创建小部件并将它们分配给变量的同一行中执行此操作时,即button_2and label_5,该值None将存储在该小部件中。

这是更正后的代码:

import tkinter as tk


class Test:
    def __init__(self):
        self.master = tk.Tk()
        self.master.geometry('550x550')

        self.label_5 = tk.Checkbutton(self.master, text="I agree to the", bg='white', width=14, font=("Arial", 8),
                                      command=self.activator)
        self.label_5.place(x=112, y=410)

        self.button_2 = tk.Button(text='Proceed', width=20, bg='white', state=tk.DISABLED, bd=1,
                                  highlightbackground='black', font=("Arial", 10))
        self.button_2.place(x=208, y=512)

        self.master.mainloop()

    def activator(self):

        if self.button_2['state'] == tk.DISABLED:
            self.button_2['state'] = tk.NORMAL

        else:
            self.button_2['state'] = tk.DISABLED


if __name__ == '__main__':
    Test()


推荐阅读