我想用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())
答案 0 :(得分: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
)
答案 1 :(得分:3)
这是正确的代码
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()