Okay, let's create a simple GUI calculator using Python's built-in tkinter library.
This calculator will feature:
A display to show input and results.
Buttons for digits (0-9).
Buttons for basic arithmetic operations (+, -, *, /).
A decimal point button (.).
An 'Equals' button (=) to perform calculations.
A 'Clear' button (C) to reset the display.
Basic error handling for invalid input or division by zero.
Python Code for Simple GUI Calculator
python
import tkinter as tk
class Calculator:
def __init__(self, master):
# Initialize the main window
self.master = master
master.title("Simple Calculator")
master.geometry("350x500") # Set initial window size
master.resizable(True, True) # Allow resizing
# --- Variables ---
self.expression = "" # Stores the current expression being built
self.equation = tk.StringVar() # Tkinter variable for the display Entry widget
# --- Display Widget ---
self.display = tk.Entry(
master,
textvariable=self.equation,
font=('Arial', 28, 'bold'), # Larger, bolder font
bd=10, # Border around the entry
insertwidth=4, # Width of the insertion cursor
width=14, # Width of the entry field (in characters)
borderwidth=4, # Borderwidth of the entry widget itself
justify='right', # Align text to the right
state='readonly' # Make it read-only, only updatable by code
)
# Position the display at the top, spanning all 4 columns
self.display.grid(row=0, column=0, columnspan=4, pady=15, padx=10, sticky="nsew")
# --- Create Buttons ---
self.create_buttons()
# --- Configure Grid for Responsiveness ---
# Make rows and columns expand equally when window is resized
for i in range(6): # 6 rows: 0 (display), 1-5 (buttons)
master.grid_rowconfigure(i, weight=1)
for i in range(4): # 4 columns
master.grid_columnconfigure(i, weight=1)
def create_buttons(self):
# Define the layout of buttons as a list of lists (rows)
# Each element is the button text
buttons_layout = [
['C', '(', ')', '/'],
['7', '8', '9', '*'],
['4', '5', '6', '-'],
['1', '2', '3', '+'],
['0', '.', '=']
]
# Define common button styling
button_font = ('Arial', 18)
button_padx = 20
button_pady = 20
# Loop through the layout to create and place buttons
row_val = 1 # Start button placement from row 1 (row 0 is for display)
for row_buttons in buttons_layout:
col_val = 0
for button_text in row_buttons:
button = None
if button_text == '=':
# Special handling for the equals button
button = tk.Button(
self.master,
text=button_text,
font=('Arial', 20, 'bold'),
padx=button_padx, pady=button_pady,
command=self.calculate,
bg='#4CAF50', fg='white' # Green background, white text
)
# The '=' button will span two columns and two rows at the end for a common calculator look
# However, for simplicity and a uniform grid, we'll keep it 1x1 for this basic version
# If we wanted to span, we'd need to adjust the layout and col_val logic.
# For *this* layout, it will just be one button.
elif button_text == 'C':
# Special handling for the clear button
button = tk.Button(
self.master,
text=button_text,
font=('Arial', 20, 'bold'),
padx=button_padx, pady=button_pady,
command=self.clear_display,
bg='#FF5722', fg='white' # Orange-red background, white text
)
elif button_text in ['/', '*', '-', '+']:
# Special styling for operator buttons
button = tk.Button(
self.master,
text=button_text,
font=button_font,
padx=button_padx, pady=button_pady,
command=lambda item=button_text: self.button_click(item),
bg='#FFC107', fg='black' # Amber background, black text
)
else:
# Regular number and decimal point buttons
button = tk.Button(
self.master,
text=button_text,
font=button_font,
padx=button_padx, pady=button_pady,
command=lambda item=button_text: self.button_click(item),
bg='#ECEFF1', fg='black' # Light grey background
)
# Place the button on the grid
if button: # Ensure a button was actually created
button.grid(row=row_val, column=col_val, sticky='nsew', padx=5, pady=5)
col_val += 1 # Move to the next column
row_val += 1 # Move to the next row after placing all buttons in a row
def button_click(self, item):
"""
Handles clicks on number and operator buttons.
Appends the clicked item to the expression string.
"""
self.expression += str(item)
self.equation.set(self.expression)
def clear_display(self):
"""
Clears the current expression and the display.
"""
self.expression = ""
self.equation.set("")
def calculate(self):
"""
Evaluates the current expression and displays the result.
Handles errors like ZeroDivisionError and SyntaxError.
"""
try:
# Use eval() to evaluate the string expression.
# NOTE: eval() can be a security risk if used with untrusted input,
# but for a simple calculator with controlled inputs, it's convenient.
result = str(eval(self.expression))
self.equation.set(result)
self.expression = result # Set the result as the new expression for chaining operations
except ZeroDivisionError:
self.equation.set("Error: Div by Zero")
self.expression = "" # Clear expression after error
except SyntaxError:
self.equation.set("Error: Invalid Input")
self.expression = "" # Clear expression after error
except Exception as e:
# Catch any other unexpected errors
self.equation.set(f"Error: {e}")
self.expression = "" # Clear expression after error
# --- Main execution block ---
if __name__ == "__main__":
root = tk.Tk() # Create the main Tkinter window
my_calculator = Calculator(root) # Create an instance of our Calculator class
root.mainloop() # Start the Tkinter event loop
How to Run the Code:
Save: Save the code above into a file named calculator.py (or any other .py name).
Run: Open a terminal or command prompt, navigate to the directory where you saved the file, and run it using:
bash
python calculator.py
Explanation:
import tkinter as tk: Imports the Tkinter library, giving it the alias tk for convenience.
class Calculator:: Encapsulates all the calculator's functionality within a class, which is good practice for organizing GUI applications.
__init__(self, master): The constructor.
self.master = master: master refers to the main Tkinter window (root in our case).
master.title("Simple Calculator"): Sets the title bar of the window.
master.geometry("350x500"): Sets the initial width and height of the window.
master.resizable(True, True): Allows the user to resize the window both horizontally and vertically.
self.expression = "": A standard Python string to build the mathematical expression (e.g., "12+5*3").
self.equation = tk.StringVar(): A special Tkinter variable that's linked to the Entry widget. When self.equation.set("...") is called, the Entry widget automatically updates its displayed text.
self.display = tk.Entry(...): Creates the input/output field at the top.
textvariable=self.equation: Links the entry's content to our tk.StringVar.
font, bd, insertwidth, width, borderwidth, justify: These are styling options for the entry widget.
state='readonly': Prevents direct typing into the display by the user, ensuring all input comes from button clicks.
self.display.grid(...): Places the display widget using the grid layout manager.
row=0, column=0: Puts it at the top-left of the grid.
columnspan=4: Makes it span all 4 columns of our button grid.
pady, padx: Adds padding around the widget.
sticky="nsew": Makes the widget expand to fill its cell in all directions (North, South, East, West) when the window is resized.
self.create_buttons(): Calls a helper method to create and lay out all the calculator buttons.
Grid Responsiveness (, ): These lines tell Tkinter to distribute extra space equally among rows and columns when the window is resized, making the buttons scale nicely.
buttons_layout: A list of lists defining the text and arrangement of the buttons.
It iterates through this buttons_layout, creating a tk.Button for each text.
It uses lambda functions for command arguments to pass the button_text to button_click, calculate, or clear_display when clicked.
button.grid(...): Places each button in its respective row_val and col_val.
sticky='nsew': Ensures buttons fill their grid cells and expand with the window.
button_click(self, item):
This function is called when a number, operator, or parenthesis button is pressed.
It appends the item (the button's text) to self.expression and updates the display via self.equation.set().
clear_display(self):
Called when the 'C' button is pressed.
Resets self.expression to an empty string and clears the display.
calculate(self):
Called when the '=' button is pressed.
try-except block: Crucial for robust error handling.
eval(self.expression): The core of the calculation. Python's built-in eval() function takes a string as input and evaluates it as a Python expression. For example, eval("10+5*2") would return 20.
ZeroDivisionError: Catches attempts to divide by zero.
Exception as e: A general catch-all for any other unexpected errors.
self.expression = result: After a successful calculation, the result becomes the new starting point for subsequent operations (e.g., if you get "15" then press "+5", it becomes "15+5").
if __name__ == "__main__":: This ensures the code inside this block only runs when the script is executed directly (not when imported as a module).
root = tk.Tk(): Creates the main window of the application.
my_calculator = Calculator(root): Creates an instance of our Calculator class, passing the main window to it. This sets up the entire GUI.
root.mainloop(): Starts the Tkinter event loop. This line keeps the window open and responsive to user interactions until it's closed.