To create a basic calculator with a graphical user interface (GUI) in Python, we can use the tkinter
library. Here's a simple Python script that implements a GUI-based calculator:
import tkinter as tk def on_button_click(event): button_text = event.widget.cget("text") if button_text == "=": try: result = eval(entry.get()) entry.delete(0, tk.END) entry.insert(tk.END, str(result)) except Exception as e: entry.delete(0, tk.END) entry.insert(tk.END, "Error") elif button_text == "C": entry.delete(0, tk.END) else: entry.insert(tk.END, button_text) root = tk.Tk() root.title("Basic Calculator") entry = tk.Entry(root, font=("Helvetica", 20)) entry.pack(ipadx=10, ipady=10) buttons_frame = tk.Frame(root) buttons_frame.pack() buttons = [ "7", "8", "9", "/", "4", "5", "6", "*", "1", "2", "3", "-", "C", "0", "=", "+" ] row, col = 0, 0 for button in buttons: btn = tk.Button(buttons_frame, text=button, font=("Helvetica", 20), padx=20, pady=10) btn.grid(row=row, column=col, padx=5, pady=5) btn.bind("", on_button_click) col += 1 if col > 3: col = 0 row += 1 root.mainloop()
Save the script in a file with a .py
extension, and run it. You will see a GUI window with buttons representing numbers, operators, and the "C" (clear) button. You can click on the buttons to perform calculations just like a regular calculator. The eval()
function is used to evaluate the mathematical expression entered in the entry field, and the result is displayed accordingly. Note that using eval()
may pose security risks if the calculator is used in an untrusted environment, so exercise caution when using this approach.