[Tutor] how to "forget" some checkbuttons on a window

Alan Gauld alan.gauld at yahoo.co.uk
Tue May 19 06:48:59 EDT 2020


On 19/05/2020 09:53, Chris Roy-Smith wrote:

> As I said to Peter Otten, I have been caught by this before, but the 
> person who showed me the flaw in my code didn't explain why there was a 
> need to separate the grid method from the widget creation. Am I better 
> off always keeping the two separate?

The only time you can combine them is for widgets that you will
NEVER need to work with again. An example might be a static
label object, once created you never change it.
But if its a label that you will update then you need to
separate them.

For anything that will be modified in any way you must store the
widget then apply grid(), pack(), place(), form() or whatever.
All the layout manager methods return None.

>> Rewriting your code above:
>>
>> var = []
>> for i in testDat:  # no need for range
>>     var.append(IntVar())
>>     e.append(Checkbutton(master, text = str(i),variable = var[-1],
>>                          onvalue = true, offvalue=False))
>>     e[-1].grid(row=i,column=0)
> 
> Is appending preferred to creating lists and lists of lists, if so I'll 
> try that out in what I have previously done in other projects.

It's not necessarily better all the time but it is better than
creating a list of dummy values and then overwriting them with
real ones.

Where you could use insertion is if you had a list of objects
keyed by some calculated index. Then you would need to create
the list and later insert the objects at the correct position.

But if you are just building a list item by item then append is
usually the best option. (Or a list comprehension which does the
same thing just a bit faster)

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list