Basic_Tkinter_Calculator.py


SUBMITTED BY: Guest

DATE: Oct. 11, 2014, 5:24 a.m.

FORMAT: Python

SIZE: 2.5 kB

HITS: 1951

  1. from tkinter import *
  2. import math
  3. while True:
  4. ans = 0
  5. root = Tk()
  6. root.wm_attributes('-topmost', 1)
  7. root.wm_title("Calculator")
  8. num_entry1 = IntVar()
  9. num_entry2 = IntVar()
  10. entry1 = Entry(root, textvariable=num_entry1, width=53)
  11. entry1.pack()
  12. entry1.delete(0, END)
  13. entry1.insert(0, "0")
  14. entry2 = Entry(root, textvariable=num_entry2, width=53)
  15. entry2.pack()
  16. entry2.delete(0, END)
  17. entry2.insert(0, "0")
  18. answer = Text(root, width=40, height=2)
  19. answer.pack()
  20. answer.insert("1.0", ans)
  21. answer.config(state=DISABLED)
  22. operation = StringVar(root)
  23. operation.set("Add")
  24. option = OptionMenu(root, operation, "Add", "Subtract", "Multiply", "Divide (Float)", "X^Y",
  25. "√num1", "√num2", "num1!", "num2!", "Pythagoras")
  26. option.pack()
  27. def calc():
  28. global ans
  29. num1 = num_entry1.get()
  30. num2 = num_entry2.get()
  31. op = operation.get()
  32. if op == 'Add':
  33. ans = num1 + num2
  34. elif op == 'Subtract':
  35. ans = num1 - num2
  36. elif op == 'Multiply':
  37. ans = num1 * num2
  38. elif op == 'Divide (Float)':
  39. ans = num1 / num2
  40. elif op == 'X^Y':
  41. ans = num1 ** num2
  42. elif op == '√num1':
  43. ans = math.sqrt(num1)
  44. elif op == '√num2':
  45. ans = math.sqrt(num2)
  46. elif op == 'num1!':
  47. ans = math.factorial(num1)
  48. elif op == 'num2!':
  49. ans = math.factorial(num2)
  50. elif op == 'Pythagoras':
  51. ans = math.sqrt(((num1 ** 2) + (num2 ** 2)))
  52. else:
  53. pass
  54. answer.config(state=NORMAL)
  55. answer.delete("1.0", END)
  56. answer.insert("1.0", ans)
  57. answer.config(state=DISABLED)
  58. return
  59. def calcquit():
  60. global z
  61. z = 1
  62. root.destroy()
  63. button1 = Button(root, text="Calculate", command=calc)
  64. button1.pack()
  65. button2 = Button(root, text="Quit", command=calcquit)
  66. button2.pack()
  67. mainloop()
  68. if z == 1:
  69. break
  70. else:
  71. pass

comments powered by Disqus