How to create multiple checkboxes from a list in a for loop in python tkinter

I have a variable length list and you want to create a checkbox (with python TKinter) for each entry in the list (each entry corresponds to a machine that should be turned on or off using the checkbox β†’ change the value to the dictionary).

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

(example, can be any length)

now the corresponding code:

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

This code creates 4 flags, but all of them are either checked or unconnected, and the values ​​in enable dict are not changed. How to solve? (I think l not working, but how to make this variable?)

+8
source share
2 answers

The "variable" passed to each control button must be an instance of the Tkinter Variable - as it is, it's just the value "0" that is passed, and that calls missbehavior.

You can create instances of Tkinter.Variable on the same for the loop in which you create the control buttons - 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() 

Then you can check the status of each flag using its get method, as in enable["ID1050"].get()

+16
source

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 this helps

+1
source

Source: https://habr.com/ru/post/903916/


All Articles