import tkinter as tk
# Добавление символа в поле
def button_click(value):
entry.insert(tk.END, value)
# Вычисление результата
def calculate():
try:
result = eval(entry.get())
entry.delete(0, tk.END)
entry.insert(0, result)
except:
entry.delete(0, tk.END)
entry.insert(0, "Ошибка")
# Очистка поля
def clear():
entry.delete(0, tk.END)
# Главное окно
window = tk.Tk()
window.title("Мини-калькулятор")
window.geometry("300x350")
window.resizable(False, False)
# Поле вывода
entry = tk.Entry(
window,
font=("Arial", 20),
justify="right",
width=15
)
entry.grid(row=0, column=0, columnspan=4, padx=10, pady=10)
# Кнопки
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),
("0", 4, 0),
("C", 4, 1),
("=", 4, 2),
("+", 4, 3)
]
for text, row, column in buttons:
if text == "C":
command = clear
elif text == "=":
command = calculate
else:
command = lambda value=text: button_click(value)
tk.Button(
window,
text=text,
font=("Arial", 16),
width=5,
height=2,
command=command
).grid(
row=row,
column=column,
padx=3,
pady=3
)
# Запуск
window.mainloop()