如何创建一个按钮来选择所有的checkbutton

2024-06-16 11:24:43 发布

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

我想用TkInter在Python中创建一个复选框列表,并尝试用一个按钮选中所有复选框。在

from tkinter import *
def create_cbuts():
for i in cbuts_text:
    cbuts.append(Checkbutton(root, text = i).pack())

def select_all():
    for j in cbuts:
        j.select()

root = Tk()
cbuts_text = ['a','b','c','d']
cbuts = []
create_cbuts()
Button(root, text = 'all', command = select_all()).pack()
mainloop()

我担心他没有填写这个名单cbuts

^{pr2}$

Tags: textinfrom列表fortkinterdefcreate
2条回答

这是正确的代码

from tkinter import *

def create_cbuts():
    for index, item in enumerate(cbuts_text):
        cbuts.append(Checkbutton(root, text = item))
        cbuts[index].pack()

def select_all():
    for i in cbuts:
        i.select()

def deselect_all():
    for i in cbuts:
        i.deselect()

root = Tk()

cbuts_text = ['a','b','c','d']
cbuts = []
create_cbuts()
Button(root, text = 'all', command = select_all).pack()
Button(root, text = 'none', command = deselect_all).pack()
mainloop()

替换:

Button(root, text = 'all', command = select_all()).pack()

有:

^{pr2}$

Checkbutton(root, text = i).pack()返回None。所以实际上是在列表中添加Nones。您需要做的是:附加Button的实例,而不是.pack()返回的值(None

相关问题 更多 >