[Tutor] My best GUI app so far.
jfouhy at paradise.net.nz
jfouhy at paradise.net.nz
Tue Jan 11 03:52:13 CET 2005
Quoting "Jacob S." <keridee at jayco.net>:
> Is there some way that I could loop over those button definitions?
You could try something like this:
defArgs = { 'width':4,
'height':3 }
# Format: ( label, callback, grid_row, grid_column )
buttons = [ ('0', self.adddigit0, 5, 1),
('1', self.adddigit1, 4, 1),
...
('x', self.multiply, 3, 4),
...
('M+', self.memplus, 1, 1) ]
for label, callback, row, col in buttons:
Button(self,
text=label,
command=callback,
**defArgs).grid(row=row, column=col)
Things to note with this approach:
- Functions are first-class objects in python, so you can put them in lists and
things.
- You can convert between dictionaries and keyword arguments (with some
restrictions) by using **. I like to use this as a way setting default
arguments for buttons and things. Now, if you want to make your buttons bigger,
you only have to change the code in one place.
- I'm not "remembering" the buttons as I create them: they are created,
immediately gridded, and then forgotton. Tkinter still remembers them, so
everything still works. But I can't (easily) get access to them, if I wanted to
change the labels or anything. You will have to think about whether this is an
issue when you are coding --- but I don't think it is a problem here.
Also, rather than defining functions adddigit0, adddigit1, etc, you could
instead do:
def addDigit(self, digit):
self.ctb()
self.distext.set(self.distext.get() + str(digit))
and then change your callbacks:
buttons = [ ('0', lambda : self.addDigit(0), 5, 1),
('1', lambda : self.addDigit(1), 4, 1),
...
]
I remember one of my lecturers saying that if you ever find yourself cutting and
pasting when you are coding, there is something you could do better.
Hope this helps :-)
--
John.
More information about the Tutor
mailing list