Tkinter, a lot of buttons, make prog shorter?

Peter Otten __peter__ at
Sun Apr 6 22:45:30 CEST 2008

skanemupp at 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)
        command = commands[text]
    except KeyError:
        def command(n=text): 
    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": ...)


More information about the Python-list mailing list