[Tutor] loops to assign variables

Alan Gauld alan.gauld at btinternet.com
Wed Jul 26 11:11:28 CEST 2006


I'm reading the gmane news archive to see what I missed
while on vacation and noticed this. Sorry the response is
so late...

"John CORRY" <john.corry at ntlworld.com> wrote

> For example, I have 30 textentry boxes numbered from entry20 to 
> entry50.
> I have used the following code to assign the entryboxes to a local 
> name.
>
> text20 = self.wTree.get_widget("entry20")
> text21 = self.wTree.get_widget("entry21")

This is not a resonse to Johns original request but a general
comment on variable naming. It seems quite common in GUI
work for folks to use this style of entryN, buttonM etc.

But its not very programmer friendly! We wouldn't normally
call our variables var1, var2 etc it makes the intent of the code
much harder to comprehend. So we choose meaningful variable
names like width, height, name, location etc.

So why not do the same with GUI widgets? I usually prepend
a short code to indicate the type of widget, and either use the
label text or action name for the vatriable. Thus

eName ---- an entry widget for holding the name and it has
an associated label text of Name

bSave -- a button that has an assaociated action
function called save()

A one or two letter prefix should cover all widget types and
it makes the code much easier to read! Even if using GUI
builder tools it is nearly always possible to rename the
widget from the default widgetXX type name to something
meaningful using the property editor.

> I have had a go at writing a loop for the above 30 textentry boxes. 
> It
> is below, but it does not work.

If you need to loop over widgets in a collection the best way
is to simply add the widgets to a collection.

for widget in widgets:
    widget.doSomething()

Or use a dictionary:

widgets = {'Name': eName, 'Save': bSave, ...}
for widget in widgets:

in fact usually you can just navigate the widget containment
tree to access all the widgets at a given level.

Even if you are creating the widgets in bulk and don't have specific
names for each field you can still do the same thing and group
them together with a name for the group. Then load the entry
widgets into a list named by the group, for example of you have
a set of 5 arbitrary search strings that a user can specify,
you define a list called searchStrings and add the widgets to that:

for n in range(5):
    searchStrings.append(Entry(args here....))

Now we can access the seach strings with

for entry in searchStrings:
     searchString += entry.getval()

mydata.search(searchString)

Or similar techniques. There is hardly ever a good case for
using generic widgetXXX type names IMHO.

Just some stylistic considerations.

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld





More information about the Tutor mailing list