如何从python tkinter的for循环中的列表创建多个复选框 [英] How do I create multiple checkboxes from a list in a for loop in python tkinter

查看:69
本文介绍了如何从python tkinter的for循环中的列表创建多个复选框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a list of variable length and want to create a checkbox (with python TKinter) for each entry in the list (each entry corresponds to a machine which should be turned on or off with the checkbox -> change the value in the dictionary).

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

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

(example, can be any length)

现在相关代码:

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

此代码生成 4 个复选框,但它们都被勾选或取消勾选,并且 enable dict 中的值不会改变.怎么解决?(我认为 l 不起作用,但如何使这个变量?)

This code produces 4 checkboxes but they are all either ticked or unticked together and the values in the enable dict don't change. How to solve? (I think the l doesn't work, but how to make this one variable?)

推荐答案

传递给每个复选按钮的变量"必须是 Tkinter 变量的一个实例——实际上,传递的只是值0",并且这会导致错误行为.

The "variable" passed to each checkbutton must be an instance of Tkinter Variable - as it is, it is just the value "0" that is passed, and this causes the missbehavior.

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

You can create the Tkinter.Variable instances on he same for loop you create the checkbuttons - just change your code to:

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

self.root.mainloop()

然后您可以使用其 get 方法检查每个复选框的状态,如下所示启用["ID1050"].get()

You can then check the state of each checkbox using its get method as in enable["ID1050"].get()

这篇关于如何从python tkinter的for循环中的列表创建多个复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆