我正在尝试制作一个非常基本的程序,它将在labelframe中垂直显示一个窗口和一组Checkbox。我希望Checkboxes根据列表的内容自动生成。我找到了一个来自这里有类似愿望的人的条目并复制了他的代码,但我收到了错误:“TypeError:list indices必须是整数或切片,而不是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()
答案 0 :(得分:2)
循环for goal in pg:
已经为变量goal
中的每个目标文字提供了:
>>> pg = ["goal1","goal2"]
>>> for goal in pg:
... print goal
...
goal1
goal2
执行pg[goal]
后,尝试在列表中查找索引"goal1"
,这是一个错误。所以文本已经goal
(你有),变量只需要是一个新变量。
for goal in pg:
l = Checkbutton(self.LabelFramep, text=goal, variable=Variable())
l.pack()
答案 1 :(得分:0)
下面的示例生成了我能想到的最简单的类,它从列表中创建Fiddle:
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()