Reputation: 305
Is it possible to iterate the production of 3 checkbuttons in TkInter. For instance I seperatly create my 3 buttons below, but can I simplify this code by running a loop, if BtnLst is defined as so.
BtnLst = ["Power", "Temperature", "Sunlight"]
#####Loop here?
...
C1 = Checkbutton(frame, text = "Power",\
onvalue = 1, offvalue = 0, height=1, \
width = 10)
C1.pack(side=LEFT)
C2 = Checkbutton(frame, text = "Temperature",\
onvalue = 1, offvalue = 0, height=1, \
width = 10)
C2.pack(side=LEFT,padx =5, ipadx=12)
C3 = Checkbutton(frame, text = "Sunlight",\
onvalue = 1, offvalue = 0, height=1, \
width = 10)
C3.pack(side=LEFT)
Is this even possible in tkinter because I have defined all 3 buttons separately?
Upvotes: 1
Views: 73
Reputation: 76264
Sure, it's simple.
for name in BtnLst:
button = Checkbutton(frame, text=name, onvalue = 1, offvalue = 0, height=1, width = 10)
button.pack(side=LEFT)
If each element has its own unique text, configuration options, and callback functions, you can still create them in a list, but you need to hold each of these things in a collection while you iterate. I don't recomend doing this if you only have three buttons; since you're making three lists, you're not really gaining anything complexity wise. It might still be worth doing if you have, say, 30 buttons or something.
names = ["Power", "Temperature", "Sunlight"]
callbacks = [SomeOtherClass.foo, SomeOtherClass.bar, SomeOtherClass.baz]
pack_options = [{}, {"padx": 5, "ipadx":12}, {}]
for name, callback, pack_options in zip(names, callbacks, pack_options):
button = Checkbutton(frame, text=name, onvalue = 1, offvalue = 0, height=1, width = 10, command=callback)
button.pack(side=LEFT, **pack_options)
Upvotes: 5
Reputation: 532518
Use a list comprehension to create a list of buttons:
C = [Checkbutton(frame, text=x, onvalue=1, offvalue=0, height=1, width = 10)
for x in BtnList]
Then pack them as necessary.
C[0].pack(side=LEFT)
C[1].pack(side=LEFT, padx=5, ipadx=12)
C[2].pack(side=LEFT)
Upvotes: 1