Question

I'm creating a GUI calculator program with tkinter and I was wondering if I could create the buttons without making my code become excessively long (as my program will contain a lot of buttons that perform the same function but use a different value for the argument).

Code:

self.divide = tk.Button(self, text = "/", width = 4, command = lambda: self.process("/"))
self.divide.grid(row = 2, column = 3)

self.multiply = tk.Button(self, text = "*", width = 4, command = lambda: self.process("*"))
self.multiply.grid(row = 3, column = 3)

self.minus = tk.Button(self, text = "-", width = 4, command = lambda: self.process("-"))
self.minus.grid(row = 4, column = 3)

self.add = tk.Button(self, text = "+", width = 4, command = lambda: self.process("+"))
self.add.grid(row = 5, column = 3)

How would I make this code less repetitive?

Was it helpful?

Solution

You could make a buttons iterable -- I'd suggest a dict. eg.

self.buttons = {}
for i, operation in enumerate(['/','*','-','+']):
    self.buttons[operation] = tk.Button(self, text = operation,
                                        width = 4, command = lambda: self.process(operation))
    self.buttons[operation].grid(row = i+2, column = 3)

This works for the specific example given but may be non-trivial to extend.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top