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

查看:1416
本文介绍了如何从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个复选框,但它们都在一起打开或关闭,值不更改。如何解决? (我认为l不工作,但如何使这个变量?)

This code produces 4 checkboxes but they are all either on or off together and the values don't change. How to solve? (I thought the l doesn't work but how to make this one variable?)

推荐答案

checkbutton必须是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.

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

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 方法,如
enable [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天全站免登陆