karen_constantine

Untitled

Nov 10th, 2023
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.24 KB | None | 0 0
  1. import tkinter as tk
  2.  
  3. def button_click(number):
  4. current = entry.get()
  5. entry.delete(0, tk.END)
  6. entry.insert(0, current + str(number))
  7.  
  8. def clear():
  9. entry.delete(0, tk.END)
  10.  
  11. def calculate():
  12. try:
  13. result = eval(entry.get())
  14. entry.delete(0, tk.END)
  15. entry.insert(0, result)
  16. except:
  17. entry.delete(0, tk.END)
  18. entry.insert(0, "Ошибка")
  19.  
  20. # Создаем главное окно
  21. root = tk.Tk()
  22. root.title("Калькулятор")
  23.  
  24. # Создаем поле для ввода
  25. entry = tk.Entry(root, width=20)
  26. entry.grid(row=0, column=0, columnspan=4)
  27.  
  28. # Создаем кнопки для цифр и операций
  29. buttons = [
  30. '7', '8', '9', '/',
  31. '4', '5', '6', '*',
  32. '1', '2', '3', '-',
  33. '0', '.', '=', '+'
  34. ]
  35.  
  36. row_val = 1
  37. col_val = 0
  38.  
  39. for button in buttons:
  40. tk.Button(root, text=button, padx=20, pady=20, command=lambda b=button: button_click(b) if b != '=' else calculate()).grid(row=row_val, column=col_val)
  41. col_val += 1
  42. if col_val > 3:
  43. col_val = 0
  44. row_val += 1
  45.  
  46. # Кнопка для очистки
  47. tk.Button(root, text='C', padx=20, pady=20, command=clear).grid(row=row_val, column=col_val)
  48.  
  49. root.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment