【问题标题】:How to create a button to select all checkbuttons如何创建一个按钮来选择所有复选按钮
【发布时间】:2012-07-14 11:36:40
【问题描述】:

我想用 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() 不会返回您认为的结果。
  • 是的,它不会返回列表的对象。

标签: python list checkbox tkinter


【解决方案1】:

这是正确的代码

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()

【讨论】:

    【解决方案2】:

    替换:

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

    与:

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

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

    【讨论】:

    • 这并不能解决整个问题。请参阅我对这个问题的评论。
    • 啊,是的,我只看到了command 部分。我会编辑我的答案。 :)
    • 啊,好吧,这是有道理的。方法.pack()returns None
    • 你更喜欢哪个开发环境的python。因为我不喜欢空闲的调试模式。
    • 我正在使用JetBrains PyCharm开发python,很棒
    猜你喜欢
    • 1970-01-01
    • 2021-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-25
    • 1970-01-01
    • 2015-02-27
    相关资源
    最近更新 更多