Tkinter, a lot of buttons, make prog shorter?
Peter Otten
__peter__ at web.de
Sun Apr 6 16:45:30 EDT 2008
skanemupp at yahoo.se wrote:
> is there anyway to make this shorter? i hate having these big blocks
> of similar-looking code, very unaesthetic.
> maybe doesnt matter good-code-wise?
> anyway can i make some function that makes this shorter?
> like put the etiquettes on the button froma string of
> '123+456-789*0Cr/' ?
> problem is the command and lambda-func for each button is different.
You can look up the command in a dictionary:
commands = {"C": self.Clean}
top = 3
for i, text in enumerate("123+456-789*0Cr/"):
row, column = divmod(i, 4)
try:
command = commands[text]
except KeyError:
def command(n=text):
self.Display(n)
button = Button(self, text=text, command=command, width=2, height=2)
button.grid(row=top+row, column=column)
The problem with this is that the shorter code may take a bit longer to
understand, so that there is no net win for the reader. A compromise would be
to define a helper function:
def make_button(self, row, column, text, command):
# implementation left as an exercise
# use it:
self.make_button(3, 0, "1", lambda n="1": ...)
self.make_button(3, 1, "2", lambda n="2": ...)
...
Peter
More information about the Python-list
mailing list