Advertisement
Diode_exe

Untitled

May 1st, 2025
623
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 19.52 KB | None | 0 0
  1. import math
  2. from fractions import Fraction
  3. import tkinter as tk
  4. from tkinter import messagebox, simpledialog
  5. import time
  6.  
  7. def set_mode_1():
  8. global mode
  9. mode = 1
  10. root.destroy()
  11.  
  12.  
  13. def set_mode_2():
  14. global mode
  15. mode = 2
  16. root.destroy()
  17.  
  18.  
  19. mode = 0
  20. global first_number_func
  21. global second_number_func
  22. global user_input
  23. global first_number_func_is_commit
  24. global second_number_func_is_commit
  25. global choice
  26.  
  27.  
  28. root = tk.Tk()
  29. root.title("Mode")
  30. root.geometry("250x100")
  31. tk.Button(root, text="Typing based GUI", command=set_mode_1).pack(pady=5)
  32. tk.Button(root, text="Button based GUI", command=set_mode_2).pack(pady=5)
  33.  
  34.  
  35.  
  36.  
  37. root.mainloop()
  38. if mode == 1:
  39. def first_number_func():
  40. while True:
  41. try:
  42. first_number = int(simpledialog.askstring("First number", "First number to calculate?"))
  43. return first_number
  44. except ValueError:
  45. messagebox.showerror("Invalid number", "Invalid number! Please try again")
  46.  
  47. def second_number_func():
  48. while True:
  49. try:
  50. second_number = float(simpledialog.askstring("Second number", "Second number to calculate?"))
  51. return second_number
  52. except ValueError:
  53. messagebox.showerror("Invalid number", "Invalid number! Please try again")
  54.  
  55. def operation():
  56. while True:
  57. operation_calc = simpledialog.askstring("Operation", "Operation? +, -, *, /, ** (exponentiation), %, root: ")
  58. if operation_calc in {"+", "-", "*", "/", "**", "%", "root"}:
  59. return operation_calc
  60. else:
  61. messagebox.showerror("Error", "Invalid operation!")
  62.  
  63. # Call and store results
  64. first_number_func = first_number_func()
  65. second_number_func = second_number_func()
  66. operation_calc = operation()
  67.  
  68. # Perform calculation
  69. if operation_calc == "+":
  70. result = first_number_func + second_number_func
  71. messagebox.showinfo("Result", f"{result}")
  72.  
  73. elif operation_calc == "-":
  74. result = first_number_func - second_number_func
  75. messagebox.showinfo("Result", f"{result}")
  76.  
  77. elif operation_calc == "*":
  78. result = first_number_func * second_number_func
  79. messagebox.showinfo("Result", f"{result}")
  80.  
  81. elif operation_calc == "/":
  82. result = first_number_func / second_number_func
  83. messagebox.showinfo("Result", f"{result}")
  84.  
  85.  
  86. elif operation_calc == "**":
  87. result = first_number_func ** second_number_func
  88. messagebox.showinfo("Result", f"{result}")
  89.  
  90. elif operation_calc == "%":
  91. result = first_number_func * second_number_func / 100
  92. messagebox.showinfo("Result", f"{result}")
  93.  
  94. elif operation_calc in ["root", "square root"]:
  95. try:
  96. result = math.sqrt(first_number_func)
  97. messagebox.showinfo("Result", f"{result}")
  98. except ValueError:
  99. messagebox.showerror("Error", "ValueError occurred")
  100. except TypeError:
  101. messagebox.showerror("Error", "TypeError occurred")
  102.  
  103. else:
  104. messagebox.showerror("Error", "Program error. Try again.")
  105.  
  106. if mode == 2:
  107.  
  108.  
  109.  
  110. global memory
  111. memory = 0
  112. current_number_func = 0
  113.  
  114. user_input = ""
  115. first_number_func = None
  116. second_number_func = None
  117. global val
  118. val = 0
  119. first_number_func_is_commit = False
  120. second_number_func_is_commit = False
  121.  
  122. def update_display(value):
  123. global user_input
  124. if value == "." and "." in user_input:
  125. return
  126. user_input += str(value)
  127.  
  128. # Adjust font size based on input length
  129. max_font_size = 32
  130. min_font_size = 12
  131. shrink_factor = 1 # Tweak this to control shrink rate
  132. length = len(user_input)
  133. font_size = max(int(max_font_size - length * shrink_factor), min_font_size)
  134.  
  135. display_label.config(text=user_input, font=("Arial", font_size))
  136.  
  137.  
  138. def clear_display():
  139. global user_input, val
  140. global first_number_func, second_number_func
  141. global first_number_func_is_commit, second_number_func_is_commit
  142.  
  143. user_input = ""
  144. val = 0
  145. first_number_func = None
  146. second_number_func = None
  147. first_number_func_is_commit = False
  148. second_number_func_is_commit = False
  149. display_label.config(text="")
  150.  
  151. def commit_input():
  152. global first_number_func
  153. global second_number_func
  154. global user_input
  155. global first_number_func_is_commit
  156. global second_number_func_is_commit
  157. global current_number_func
  158.  
  159. try:
  160. if not first_number_func_is_commit:
  161. first_number_func = float(user_input)
  162. display_label.config(text=f"First committed: {first_number_func}")
  163. first_number_func_is_commit = True
  164. current_number_func = 1
  165. user_input = ""
  166. elif not second_number_func_is_commit:
  167. second_number_func = float(user_input)
  168. display_label.config(text=f"Second committed: {second_number_func}")
  169. second_number_func_is_commit = True
  170. current_number_func = 2
  171. user_input = ""
  172. open_window()
  173. else:
  174. display_label.config(text="Both numbers committed.")
  175. except ValueError:
  176. display_label.config(text="Invalid input!")
  177.  
  178.  
  179.  
  180. # def perform_operation():
  181. # while True:
  182. # operation_now = simpledialog.askstring("Operation", "What operation would you like to perform? +, -, *, /, **, %, root")
  183. # if operation_now in {"+", "-", "*", "/", "**", "%", "root", "stop", "bye", "exit"}:
  184. # break
  185. # messagebox.showerror("Invalid operation", "Please choose a valid operator.")
  186.  
  187. # # Moved outside loop
  188. # try:
  189. # if operation_now == "+":
  190. # result = first_number_func + second_number_func
  191. # elif operation_now == "-":
  192. # result = first_number_func - second_number_func
  193. # elif operation_now == "*":
  194. # result = first_number_func * second_number_func
  195. # elif operation_now == "/":
  196. # if second_number_func == 0:
  197. # messagebox.showerror("Error", "Cannot divide by zero.")
  198. # return
  199. # result = first_number_func / second_number_func
  200. # elif operation_now == "**":
  201. # result = first_number_func ** second_number_func
  202. # elif operation_now == "%":
  203. # result = first_number_func * second_number_func / 100
  204. # elif operation_now == "root":
  205. # result = math.sqrt(first_number_func)
  206. # elif operation_now in ["stop", "exit", "bye"]:
  207. # exit()
  208.  
  209. # messagebox.showinfo("Result", f"{result}")
  210. # except Exception as e:
  211. # messagebox.showerror("Error", str(e))
  212.  
  213. # def perform_operation_button():
  214. # tk.Button(root, text="+", font=("Arial", 18), command=clear_display).grid(row=6, column=0, columnspan=3, pady=10)
  215.  
  216.  
  217. def zero_to_display():
  218. update_display(0)
  219.  
  220. def open_window():
  221. global new_window
  222. new_window = tk.Toplevel()
  223. new_window.title("Operators")
  224. tk.Button(new_window, text="+", font=("Arial", 24), command=lambda: button_operation("+")).pack()
  225. tk.Button(new_window, text="-", font=("Arial", 24), command=lambda: button_operation("-")).pack()
  226. tk.Button(new_window, text="*", font=("Arial", 24), command=lambda: button_operation("*")).pack()
  227. tk.Button(new_window, text="/", font=("Arial", 24), command=lambda: button_operation("/")).pack()
  228. tk.Button(new_window, text="**", font=("Arial", 24), command=lambda: button_operation("**")).pack()
  229. tk.Button(new_window, text="%", font=("Arial", 24), command=lambda: button_operation("%")).pack()
  230. tk.Button(new_window, text="root", font=("Arial", 24), command=lambda: button_operation("root")).pack()
  231. tk.Button(new_window, text="cancel", font=("Arial", 24), command=lambda: button_operation("cancel")).pack()
  232. tk.Button(new_window, text="close", font=("Arial", 24), command=lambda: button_operation("close")).pack()
  233.  
  234. def button_operation(selection):
  235. try:
  236. if selection == "+":
  237. result = first_number_func + second_number_func
  238. messagebox.showinfo("Result", f"{result}")
  239. elif selection == "-":
  240. result = first_number_func - second_number_func
  241. messagebox.showinfo("Result", f"{result}")
  242. elif selection == "*":
  243. result = first_number_func * second_number_func
  244. messagebox.showinfo("Result", f"{result}")
  245. elif selection == "/":
  246. if second_number_func == 0:
  247. messagebox.showerror("Error", "Cannot divide by zero! Press cancel and try again")
  248. return
  249. result = first_number_func / second_number_func
  250. messagebox.showinfo("Result", f"{result}")
  251. elif selection == "**":
  252. result = first_number_func ** second_number_func
  253. messagebox.showinfo("Result", f"{result}")
  254. elif selection == "%":
  255. result = first_number_func * second_number_func / 100
  256. messagebox.showinfo("Result", f"{result}")
  257. elif selection == "root":
  258. result = math.sqrt(first_number_func)
  259. messagebox.showinfo("Result", f"{result}")
  260. elif selection == "cancel":
  261. new_window.destroy()
  262. elif selection == "close":
  263. answer = messagebox.askyesno("Close?", "Are you sure you want to close the calculator?")
  264. if answer:
  265. root.destroy() # cleaner than exit()
  266. except Exception as e:
  267. messagebox.showerror("Error", str(e))
  268.  
  269. def clear_entry():
  270. global first_number_func, second_number_func
  271. global first_number_func_is_commit, second_number_func_is_commit
  272. global current_number_func, user_input
  273. if current_number_func == 1:
  274. first_number_func = 0
  275. first_number_func_is_commit = False
  276. user_input = ""
  277. display_label.config(text="First entry cleared")
  278. elif current_number_func == 2:
  279. current_number_func = 1
  280. second_number_func = 0
  281. second_number_func_is_commit = False
  282. user_input = ""
  283. display_label.config(text="Second entry cleared")
  284.  
  285. def close_calc():
  286. answer = messagebox.askyesno("Close?", "Are you sure you want to close the calculator?")
  287. if answer:
  288. root.destroy() # cleaner than exit()
  289.  
  290. choice = None
  291.  
  292. global choice_for_func
  293.  
  294. def memory_save_type():
  295. dialog = tk.Toplevel()
  296. dialog.title("Custom Dialog")
  297. dialog.grab_set() # Makes it modal
  298. def choice_func(choice):
  299.  
  300. if choice == "result":
  301. choice_for_func = "result"
  302. elif choice == "first_number":
  303. choice_for_func == "first_number"
  304. elif choice == "second_number":
  305. choice_for_func == "second_number"
  306.  
  307. tk.Label(dialog, text="What to save to memory?", font=("Arial", 14)).pack(pady=10)
  308. tk.Button(dialog, text="Result", command=lambda: choice("result")).pack(pady=5)
  309. tk.Button(dialog, text="First number", command=lambda: choice("first_number")).pack(pady=5)
  310. tk.Button(dialog, text="Second number", command=lambda: choice("second_number")).pack(pady=5)
  311. # def choice(option):
  312. # tk.Button(dialog, text="Result", command=lambda: choice("result")).pack(pady=5)
  313. # tk.Button(dialog, text="First number", command=lambda: choice("first_number")).pack(pady=5)
  314. # tk.Button(dialog, text="Second number", command=lambda: choice("second_number")).pack(pady=5)
  315.  
  316. # GUI Setup
  317. root = tk.Tk()
  318. root.title("Calculator")
  319.  
  320. def key_pressed(event):
  321. global user_input
  322. key = event.char
  323. keysym = event.keysym
  324. print(f"Key pressed: {event.char}")
  325. if key.isdigit() or key == ".":
  326. update_display(key)
  327. elif keysym == "BackSpace":
  328. user_input = user_input[:-1]
  329. display_label.config(text=user_input)
  330. elif key.lower() == "c": # clear
  331. clear_display()
  332. elif key == "\r": # Enter key
  333. commit_input()
  334. elif key == "\b":
  335. update_display(key)
  336. elif event.keysym == "BackSpace":
  337. update_display(key)
  338. # Add more as needed
  339.  
  340.  
  341. root.bind("<Key>", key_pressed)
  342.  
  343.  
  344. display_label = tk.Label(root, text="", font=("Arial", 24))
  345. display_label.grid(row=0, column=0, columnspan=3, pady=10)
  346.  
  347. # Number Buttons
  348. def sin_func():
  349. result = math.sin(first_number_func)
  350. messagebox.showinfo("sin result", f"{result}")
  351. def cos_func():
  352. result = math.cos(first_number_func)
  353. messagebox.showinfo("cos result", f"{result}")
  354. def tan_func():
  355. result = math.tan(first_number_func)
  356. messagebox.showinfo("tan result", f"{result}")
  357.  
  358. def add_to_memory():
  359. global memory, result, choice_for_func
  360. def memory_save_type():
  361. dialog = tk.Toplevel()
  362. dialog.title("Memory editor")
  363. dialog.grab_set()
  364.  
  365. def choice_func(choice):
  366. nonlocal dialog
  367. global memory, result, first_number_func, second_number_func
  368. if choice == "result":
  369. try:
  370. memory += result
  371. except NameError:
  372. messagebox.showerror("Memory error", "No result available")
  373. except TypeError:
  374. messagebox.showerror("Memory error", "No result available, did not save")
  375. elif choice == "first_number":
  376. try:
  377. memory += first_number_func
  378. except NameError:
  379. messagebox.showerror("Memory error", "No first number")
  380. except TypeError:
  381. messagebox.showerror("Memory error", "First number not defined, press commit first!")
  382. elif choice == "second_number":
  383. try:
  384. memory += second_number_func
  385. except NameError:
  386. messagebox.showerror("Memory error", "No second number")
  387. except TypeError:
  388. messagebox.showerror("Memory error", "Second number not defined, press commit first!")
  389. dialog.destroy()
  390. messagebox.showinfo("Memory Updated", f"Memory now: {memory}")
  391.  
  392. tk.Label(dialog, text="Add what to memory?", font=("Arial", 14)).pack(pady=10)
  393. tk.Button(dialog, text="Result", command=lambda: choice_func("result")).pack(pady=5)
  394. tk.Button(dialog, text="First number", command=lambda: choice_func("first_number")).pack(pady=5)
  395. tk.Button(dialog, text="Second number", command=lambda: choice_func("second_number")).pack(pady=5)
  396.  
  397. memory_save_type()
  398.  
  399.  
  400. def subtract_from_memory():
  401. def memory_save_type():
  402. dialog = tk.Toplevel()
  403. dialog.title("Memory editor")
  404. dialog.grab_set()
  405.  
  406. def choice_func(choice):
  407. nonlocal dialog
  408. global memory, result, first_number_func, second_number_func
  409. if choice == "result":
  410. try:
  411. memory -= result
  412. except NameError:
  413. messagebox.showerror("Memory error", "No result available")
  414. except TypeError:
  415. messagebox.showerror("Memory error", "No result available, did not save")
  416. elif choice == "first_number":
  417. try:
  418. memory -= first_number_func
  419. except NameError:
  420. messagebox.showerror("Memory error", "No first number")
  421. except TypeError:
  422. messagebox.showerror("Memory error", "First number not defined, press commit first!")
  423. elif choice == "second_number":
  424. try:
  425. memory -= second_number_func
  426. except NameError:
  427. messagebox.showerror("Memory error", "No second number")
  428. except TypeError:
  429. messagebox.showerror("Memory error", "Second number not defined, press commit first!")
  430. dialog.destroy()
  431. messagebox.showinfo("Memory Updated", f"Memory now: {memory}")
  432.  
  433. tk.Label(dialog, text="Subtract what from memory?", font=("Arial", 14)).pack(pady=10)
  434. tk.Button(dialog, text="Result", command=lambda: choice_func("result")).pack(pady=5)
  435. tk.Button(dialog, text="First number", command=lambda: choice_func("first_number")).pack(pady=5)
  436. tk.Button(dialog, text="Second number", command=lambda: choice_func("second_number")).pack(pady=5)
  437.  
  438. def clear_memory():
  439. memory = 0
  440. messagebox.showinfo("Memory", f"Memory now: {memory}")
  441. def recall_memory():
  442. messagebox.showinfo("Memory", f"Memory now: {memory}")
  443.  
  444.  
  445. tk.Button(root, text="sin", font=("Arial", 15), width=1, height=1, command=sin_func).grid(row=5, column=0)
  446. tk.Button(root, text="cos", font=("Arial", 15), width=1, height=1, command=cos_func).grid(row=5, column=1)
  447. tk.Button(root, text="tan", font=("Arial", 15), width=1, height=1, command=tan_func).grid(row=5, column=2)
  448.  
  449. tk.Button(root, text="M+", font=("Arial", 15), width=1, height=1, command=lambda: add_to_memory()).grid(row=1, column=3)
  450. tk.Button(root, text="M-", font=("Arial", 15), width=1, height=1, command=lambda: subtract_from_memory()).grid(row=2, column=3)
  451. tk.Button(root, text="MC", font=("Arial", 15), width=1, height=1, command=lambda: clear_memory()).grid(row=3, column=3)
  452. tk.Button(root, text="MR", font=("Arial", 15), width=1, height=1, command=lambda: recall_memory()).grid(row=4, column=3)
  453.  
  454. for i in range(9):
  455. row = (i // 3) + 1
  456. col = i % 3
  457. tk.Button(root, text=str(i + 1), font=("Arial", 18),
  458. command=lambda val=i+1: update_display(val)).grid(row=row, column=col, padx=5, pady=5)
  459.  
  460. tk.Button(root, text="0", font=("Arial", 15), width=1, height=1, command=zero_to_display).grid(row=4, column=1)
  461. tk.Button(root, text=".", font=("Arial", 15), width=1, height=1, command=lambda: update_display(".")).grid(row=4, column=0)
  462.  
  463. # Commit Button
  464. tk.Button(root, text="Commit", font=("Arial", 18), command=commit_input).grid(row=6, column=0, columnspan=3, pady=10)
  465. tk.Button(root, text="Clear All", font=("Arial", 18), command=clear_display).grid(row=7, column=0, columnspan=2, pady=10)
  466. tk.Button(root, text="Clear Entry", font=("Arial", 18), command=clear_entry).grid(row=7, column=2, columnspan=2, pady=10)
  467. tk.Button(root, text="Close", font=("Arial", 18), command=close_calc).grid(row=8, column=0, columnspan=3, pady=10)
  468.  
  469. root.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement