import tkinter as tk
def add_digit(digit):
value = entry.get() + str(digit)
entry.delete(0, 'end')
entry.insert('end', value)
def clear():
entry.delete(0, 'end')
def calculate():
try:
result = eval(entry.get())
if int(result) == float(result):
result = int(result)
entry.delete(0, 'end')
entry.insert('end', result)
except Exception:
entry.delete(0, 'end')
entry.insert('end', 'Ошибка!')
root = tk.Tk()
root.title('Калькулятор')
root.geometry('280x360')
root.resizable(False, False)
entry = tk.Entry(root, justify='right', font='Arial 14 bold')
entry.grid(row=0, column=0, columnspan=4, sticky='we', padx=5, pady=5)
buttons = [
('7', 1, 0),
('8', 1, 1),
('9', 1, 2),
('/', 1, 3),
('4', 2, 0),
('5', 2, 1),
('6', 2, 2),
('*', 2, 3),
('1', 3, 0),
('2', 3, 1),
('3', 3, 2),
('-', 3, 3),
('C', 4, 0),
('0', 4, 1),
('=', 4, 2),
('+', 4, 3)
]
for btn_text, row, col in buttons:
def on_click(text=btn_text):
if text.isdigit():
add_digit(int(text))
elif text == '=':
calculate()
elif text == 'C':
clear()
else:
entry.insert('end', text)
button = tk.Button(
root, text=btn_text, bd=3, relief='raised',
command=on_click, font='Arial 14'
)
button.grid(row=row, column=col, stick='wens', padx=5, pady=5)
for i in range(4):
root.grid_rowconfigure(i, weight=1)
for j in range(4):
root.grid_columnconfigure(j, weight=1)
root.mainloop()