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

后端 未结 2 457
我在风中等你
我在风中等你 2020-12-09 12:07

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 o

相关标签:
2条回答
  • 2020-12-09 12:56

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

    0 讨论(0)
  • 2020-12-09 13:00

    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

    0 讨论(0)
提交回复
热议问题