2011-12-16 248 views
6

我有一个可变长度列表,并且希望为列表中的每个条目创建一个复选框(使用python TKinter)(每个条目对应一个机器应该用复选框打开或关闭 - >更改字典中的值)。如何在python tkinter的for循环中的列表中创建多个复选框

print enable 
{'ID1050': 0, 'ID1106': 0, 'ID1104': 0, 'ID1102': 0} 

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

现在相关的代码:

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

此代码生成4个复选框但它们都要么打勾或取消选中在一起,并在该值enable字典不改变。怎么解决? (我认为l不起作用,但如何使这一个变量?)

回答

12

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

您可以在他创建Tkinter.Variable情况相同的for循环创建checkbuttons - 只是改变你的代码:

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

+0

谢谢!复选框现在可用,只有一个问题:我如何读取tkinter类之外的变量(我已将它设置为:http://stackoverflow.com/a/1835036/1102225)。 我尝试了一切。当我使用`print enable [machine] .get() AttributeError:'int'object has no attribute'get'` 因此我尝试了: `print app.enable [machine] .get() AttributeError:'MyTkApp 'object has no attribute'enable'` (app是tkinter类的对象,叫做MyTkApp) 当我没有得到它的时候: `print enable [machine] PY_VAR0` – Sebastian 2011-12-19 10:57:22

1

只是想分享一个列表,而不是一本字典我的例子:

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

希望它有帮助

相关问题