Steven Matthews
Steven Matthews

Reputation: 11285

How to write this more "Pythonically"

So I'm trying to write a group of checkboxes (I actually should probably write it as a class, because it is very possible we'll add additional ones)

So far I've got this, but this repeats code and so isn't very efficient. In what ways can I make the code more elegant?

var1 = IntVar()
var2 = IntVar()
var3 = IntVar()

c1 = Checkbutton(text="Snagit", variable=var1)
c1.pack()

c2 = Checkbutton(text="Camtasia", variable=var2)
c2.pack()

c3 = Checkbutton(text="GotoMeeting", variable=var3)
c3.pack()

app.mainloop()

check1 = var1.get()
check2 = var2.get()
check3 = var3.get()

Upvotes: 2

Views: 1332

Answers (5)

Jeffrey Greenham
Jeffrey Greenham

Reputation: 1432

vars = [IntVar() for i in xrange(3)]
buttons = [Checkbutton(text="Snagit", variable=vars[0]),Checkbutton(text="Camtasia", variable=vars[1]),Checkbutton(text="GotoMeeting", variable=vars[2])]
for c in buttons:
  c.pack()

app.mainloop()
check1,check2,check3  = [v.get() for v in vars]

I don't know if this is Pythonic, but I think it's a bit cleaner.

Upvotes: 0

Tim Lesher
Tim Lesher

Reputation: 6441

Accumulate the variables and create the buttons inline:

variables = []
for text in ['Snagit', 'Camtasia', 'Gotomeeting']:
    variable = IntVar()
    Checkbutton(text=text, variable=variable).pack()
    variables.append(variable)

app.mainloop()

checks = [variable.get() for variable in variables]

Upvotes: 2

Marcin
Marcin

Reputation: 49826

vars = {}
buttons = {}

for text in ('Snagit', 'Camtasia', 'GotoMeeting'):
    vars[text] = IntVar()
    buttons[text] = Checkbutton(text=text, variable=vars[text])
    buttons[text].pack()


app.mainloop()

checks = [var.get() for var in vars.values()]

By using dicts and tuples, you eliminate repetition. This isn't as sexy as some of the solutions using only generators, but there's no reason to do that here, and I think this is rather more readable.

Upvotes: 2

Jesse
Jesse

Reputation: 5084

Here's a quick example of how to use a loop to make this a little better:

check_names = ["Snagit", "Camtasia", "GotoMeeting"]
variables = []
for name in check_names:
    variables.append(IntVar())
    Checkbutton(text=name, variable=variables[-1]).pack()

app.mainloop()
checks = [variable.get() for variable in variables]

Upvotes: 3

Sanjay T. Sharma
Sanjay T. Sharma

Reputation: 23208

I propose this solution though the use of itertools module might look a bit daunting but I swear learning it is for your own good! :)

labels = ("snagit", "camtasia", "gotomeeting")
vars = [IntVar() for _ in labels]
for name, v in itertools.izip(labels, vars):
    Checkbutton(text=name, variable=v).pack()
app.mainloop()
checks = [v.get() for v in vars]

Upvotes: 3

Related Questions