如何选中复选框以启用Tkinter中的按钮

2024-10-16 20:52:46 发布

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

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

我想在选中checkbutton后启用“继续”按钮,但我似乎无法找到它


Tags: textselfplacebuttonwidthlabeltkbg
1条回答
网友
1楼 · 发布于 2024-10-16 20:52:46

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

  • 在将名为activator的函数作为self.activator引用给Buttonbutton_2)的函数时,必须将其作为command引用
  • 必须将名为activator的函数的parameter名为button更改为self
  • 您需要做的最重要的事情是将代码中放置Buttonbutton_2)和Checkbuttonlabel_5)的部分移动到新行。就像我在下面的代码中所做的那样。这样做的原因是packgridplace总是return{}。当您在创建小部件并将其分配给变量的同一行中执行此操作时,即button_2label_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()

相关问题 更多 >