
import tkinter as tk
def on_click(event):
text = event.widget.cget("text")
if text == "=":
try:
result = eval(str(screen.get()))
screen.set(result)
except Exception as e:
screen.set("Error")
elif text == "C":
screen.set("")
else:
current = screen.get()
screen.set(current + text)
# Creating main window
root = tk.Tk()
root.title("Simple Calculator")
root.geometry("300x400")
# StringVar for the screen
tk.Label(root, text="Calculator", font="lucida 20 bold").pack()
screen = tk.StringVar()
screen_entry = tk.Entry(root, textvar=screen, font="lucida 20 bold", justify='right')
screen_entry.pack(fill=tk.BOTH, ipadx=8, pady=10, padx=10)
# Adding buttons
button_frame = tk.Frame(root)
button_frame.pack()
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),
("C", 4, 0), ("0", 4, 1), ("=", 4, 2), ("+", 4, 3),
]
for (text, row, col) in buttons:
button = tk.Button(button_frame, text=text, font="lucida 15 bold", width=4, height=2)
button.grid(row=row, column=col, padx=5, pady=5)
button.bind("<Button-1>", on_click)
# Running the main loop
root.mainloop()
pip install pyinstaller
2. Run PyInstaller on your Python file to create an executable:
pyinstaller --onefile your_script.py
This command will bundle your calculator script into a single executable file, allowing you to share it without requiring users to have Python installed.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.