import tkinter as tki class MyCalculatorApp: NUM_DIGITS = 10 def __init__(self,parent): self._parent = parent self._display_label = tki.Label(parent) self._display_label.pack(side=tki.TOP) lower_frame = tki.Frame(parent) lower_frame.pack() self._create_digit_buttons(lower_frame) self._create_op_buttons(lower_frame) self._reset() def _reset(self): self._display_label.configure(text="0") self._current_num = "" self._prev_num = 0 self._prev_op = lambda x, y: x+y def _create_digit_buttons(self,parent): digit_frame = tki.Frame(parent) digit_frame.pack(side=tki.LEFT) button = [None]*MyCalculatorApp.NUM_DIGITS for digit in range(MyCalculatorApp.NUM_DIGITS): button[digit] = tki.Button(digit_frame, text=str(digit), command=self._digit_event_h(digit)) button[digit].grid(row = 3-(digit+2)//3, column=(digit-1)%3) def _create_op_buttons(self,parent): separator = tki.Frame(parent, width=10) separator.pack(side = tki.LEFT) op_frame = tki.Frame(parent) op_frame.pack(side=tki.LEFT) plus_button = tki.Button(op_frame,text="+", command=self._op_event_h(lambda x, y: x+y)) times_button = tki.Button(op_frame,text="*", command=self._op_event_h(lambda x, y: x*y)) op_equals = lambda x, y: x if self._current_num == "" else y eq_button = tki.Button(op_frame, text="=", command=self._op_event_h(op_equals)) clear_button = tki.Button(op_frame, text="C", command=self._reset) plus_button.pack(side=tki.TOP) times_button.pack(side=tki.TOP) eq_button.pack(side=tki.TOP) clear_button.pack(side=tki.TOP) def _digit_event_h(self,digit): def digit_press(): self._current_num += str(digit) self._display_label.configure(text = self._current_num) return digit_press def _op_event_h(self,op_func): def op_event(): if self._current_num == "": cur_num = 0 else: cur_num = int(self._current_num) self._prev_num = self._prev_op(self._prev_num,int(cur_num)) self._prev_op = op_func self._current_num = "" self._display_label.configure(text=str(self._prev_num)) return op_event root = tki.Tk() root.wm_title("My Simple Calculator") MyCalculatorApp(root) root.mainloop()