【问题标题】:How to create Checkboxes from list如何从列表中创建复选框
【发布时间】:2018-01-04 05:56:39
【问题描述】:

我现在正在尝试制作一个非常基本的程序,它将在标签框中垂直显示一个窗口和一组复选框。我希望复选框根据列表的内容自动生成。我在这里找到了一个有类似愿望的人的条目并复制了他的代码,但我收到了错误:“TypeError: list indices must be integers or slices, not str”

我是 Python 新手,尝试了所有方法来纠正这个问题,但还是失败了。任何帮助都会很棒!完整代码如下:

from tkinter import *

#list to be used to make Checkboxes
pg = ["goal1","goal2"]


class yeargoals:
global pg
def __init__(self,master):
    self.master = master
    master.title("This Year's Goals")

    #Makes the label Fram I want the Checkboxes to go in
    self.LabelFramep= LabelFrame()
    self.LabelFramep.configure(width=210)

    #Makes the Checkboxs from the list above
    for goal in pg:
        pg[goal] = Variable()
        l = Checkbutton(self.LabelFramep, text=goal, variable=pg[goal])
        l.pack()


root = Tk()
Window = yeargoals(root)
root.mainloop()

【问题讨论】:

  • 错误信息非常简单;您用于列表索引的变量是一个字符串,需要先转换为 int。我还没有真正查看过您的代码,但在我的脑海中,可能是 goal 变量给您带来了问题。

标签: python checkbox tkinter


【解决方案1】:

循环for goal in pg: 已经在变量goal 中为您提供了每个目标文本:

>>> pg = ["goal1","goal2"]
>>> for goal in pg:
...   print goal
...
goal1
goal2

当您执行pg[goal] 时,这是在尝试在列表中查找索引"goal1",这是一个错误。所以 text 已经是 goal (你有)并且变量只需要是一个新变量。

for goal in pg:
    l = Checkbutton(self.LabelFramep, text=goal, variable=Variable())
    l.pack()

【讨论】:

  • 工作就像一个魅力!谢谢!
  • 谢谢!快速跟进,当我这样做时,我还有办法检查每个复选框的状态吗?这里的最终目标不仅是创建这些,而且当检查一个总数量增加 1 时。
  • 如果要计算复选框,请使用enumerate(),如下所示:for i, goal in enumerate(pg, start=1)。然后i 有运行索引,从0 开始(我已经完成了start=1,因为你想要一个计数)。
【解决方案2】:

下面的例子产生了我能想到的最简单的类,它从列表中创建check buttons

import tkinter as tk

class CheckbuttonList(tk.LabelFrame):
    def __init__(self, master, text=None, list_of_cb=None):
        super().__init__(master)

        self['text'] = text
        self.list_of_cb = list_of_cb
        self.cb_values = dict()
        self.check_buttons = dict()

        if self.list_of_cb:
            for item in list_of_cb:
                self.cb_values[item] = tk.BooleanVar()
                self.check_buttons[item] = tk.Checkbutton(self, text=item)
                self.check_buttons[item].config(onvalue=True, offvalue=False,
                                            variable=self.cb_values[item])
                self.check_buttons[item].pack()



if __name__ == '__main__':

    root = tk.Tk()

    my_list = ["item1", "item2", "item3"]

    my_cbs = CheckbuttonList(root, "My Checkbox List", my_list)
    my_cbs.pack()

    root.mainloop()

【讨论】:

    猜你喜欢
    • 2014-06-12
    • 2015-05-22
    • 2016-02-29
    • 1970-01-01
    • 2014-12-31
    • 2016-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多