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

4
我想使用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
cbuts.append(Checkbutton(root, text = i).pack())

Checkbutton(root, text=i).pack()并不会返回你想要的结果。 - Joel Cornett
是的,它并没有返回列表的对象。 - Abi
2个回答

5
以下是正确的代码:
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()

3

替换:

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

使用:

Button(root, text='all', command=select_all).pack()
Checkbutton(root, text = i).pack() 返回的是None,所以实际上你只是将None添加到了列表中。你需要做的是:添加Button的实例而不是.pack()返回的值(None)。

这并没有解决整个问题。请看我在问题上的评论。 - Joel Cornett
啊,是的,我只看到了“command”部分。我会编辑我的答案。 :) - UltraInstinct
啊,好的,那就有道理了。方法.pack()返回None - Abi
你更喜欢哪个Python开发环境?因为我不喜欢IDLE的调试模式。 - Abi
我正在使用JetBrains PyCharm来开发Python,它非常棒。 - Pooya

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接