如何在python tkinter中从for循环中的列表创建多个复选框

如何在python tkinter中从for循环中的列表创建多个复选框,python,checkbox,for-loop,tkinter,Python,Checkbox,For Loop,Tkinter,我有一个可变长度的列表,希望为列表中的每个条目创建一个复选框(使用python TKinter)(每个条目对应一台机器,应该通过复选框->更改字典中的值来打开或关闭) (例如,可以是任意长度) 现在,相关代码: for machine in enable: l = Checkbutton(self.root, text=machine, variable=enable[machine]) l.pack() self.root.mainloop() 此代码生成4个复选框,但它们都

我有一个可变长度的列表,希望为列表中的每个条目创建一个复选框(使用python TKinter)(每个条目对应一台机器,应该通过复选框->更改字典中的值来打开或关闭)

(例如,可以是任意长度)

现在,相关代码:

for machine in enable:
    l = Checkbutton(self.root, text=machine, variable=enable[machine])
    l.pack()
self.root.mainloop()
此代码生成4个复选框,但它们都被勾选或取消勾选在一起,并且
启用
dict中的值不会更改。如何解决?(我认为
l
不起作用,但是如何使这一个变量?

传递给每个checkbutton的“变量”必须是Tkinter变量的一个实例-实际上,传递的只是值“0”,这会导致错误行为

您可以在创建checkbuttons的同一循环上创建Tkinter.Variable实例-只需将代码更改为:

for machine in enable:
    enable[machine] = Variable()
    l = Checkbutton(self.root, text=machine, variable=enable[machine])
    l.pack()

self.root.mainloop()
然后,您可以使用其
get
方法检查每个复选框的状态,如中所示
enable[“ID1050”].get()

我只是想分享我的示例,以获得一个列表而不是一个字典:

from Tkinter import *

root = Tk()    

users = [['Anne', 'password1', ['friend1', 'friend2', 'friend3']], ['Bea', 'password2', ['friend1', 'friend2', 'friend3']], ['Chris', 'password1', ['friend1', 'friend2', 'friend3']]]

for x in range(len(users)):
    l = Checkbutton(root, text=users[x][0], variable=users[x])
    print "l = Checkbutton(root, text=" + str(users[x][0]) + ", variable=" + str(users[x])
    l.pack(anchor = 'w')

root.mainloop()

希望对您有所帮助

谢谢!复选框现在起作用了,只有一个问题:如何读取tkinter类之外的变量(我将其设置为:)。我什么都试过了。当我使用
print enable[machine].get()AttributeError:'int'对象没有属性'get'
时,我尝试:
print app.enable[machine].get()AttributeError:'MyTkApp'对象没有属性'enable'
(app是名为MyTkApp的tkinter类的对象),当我在没有get的情况下执行时:
print enable[machine]PY_VAR0
哦,我自己买的!我在tkinter类中包含了一个函数来返回值:
def read(self,machine):返回enable[machine].get()
,然后在类之外,您可以调用:
print app.read(1050)
对python3使用tkinter和print with()
from Tkinter import *

root = Tk()    

users = [['Anne', 'password1', ['friend1', 'friend2', 'friend3']], ['Bea', 'password2', ['friend1', 'friend2', 'friend3']], ['Chris', 'password1', ['friend1', 'friend2', 'friend3']]]

for x in range(len(users)):
    l = Checkbutton(root, text=users[x][0], variable=users[x])
    print "l = Checkbutton(root, text=" + str(users[x][0]) + ", variable=" + str(users[x])
    l.pack(anchor = 'w')

root.mainloop()