Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create multiple checkboxes from a list in a for loop in 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)

now the relevant code:

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

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

like image 318
Sebastian Avatar asked Dec 16 '11 15:12

Sebastian


People also ask

How to create multiple checkbox in tkinter?

A tkinter checkbox can be created using the tkinter checkbutton widget. It allow users to select multiple options or choices from a number of different options. They are different from a radio button because in a radio button users can make only one choice, but checkbox allows multiple choices.

What are checkboxes Python?

The Checkbutton widget is used to display a number of options to a user as toggle buttons. The user can then select one or more options by clicking the button corresponding to each option. You can also display images in place of text.


2 Answers

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.

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

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

like image 80
jsbueno Avatar answered Oct 19 '22 03:10

jsbueno


Just thought I'd share my example for a list instead of a dictionary:

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

Hope it helps

like image 26
kidchrono Avatar answered Oct 19 '22 04:10

kidchrono