Python, Tkinter: 获取选中复选框的文本
我正在处理以下代码。我的目标是当一个复选按钮被选中时,获取它的文本,并把这个文本添加到一个列表中。我想动态地写这段代码,因为列表'x'的大小可能会变化。以下是我目前的代码:
from Tkinter import *
root = Tk()
global j
j = []
x = ['hello', 'this', 'is', 'a', 'list']
def chkbox_checked():
j.append(c.cget("text"))
for i in x:
c = Checkbutton(root, text=i, command=chkbox_checked)
c.grid(sticky=W)
mainloop()
print j
到目前为止,我得到的j的输出是:
['list', 'list', 'list', 'list', 'list'] #depending on how many Checkbuttons I select
我希望得到的输出是这样的:
['this', 'list'] #depending on the Checkbuttons that I select; this would be the output if I
#selected Checkbuttons "this" and "list".
我尝试过在复选按钮中使用“变量”选项,但似乎没有搞清楚怎么连接这些点。有没有人能给我指个方向?我觉得这应该是相对简单的。谢谢!
1 个回答
2
问题在于,for循环中的变量c在每次循环时都会被重新赋值。这就是为什么它只打印出列表list
中的最后一个元素。
一种解决办法是使用lambda函数。
def chkbox_checked(text):
return lambda : j.append(text)
for i in x:
c = Checkbutton(root, text=i, command=chkbox_checked(i))
c.grid(sticky=W)