Explanation of Tkinter Calculator Code
This document provides a line-by-line explanation of the Python code for a simple
calculator application using the tkinter library. Tkinter is a standard GUI (Graphical User
Interface) toolkit in Python.
Importing Modules
import tkinter as tk
from tkinter import *
- **`import tkinter as tk`**: Imports the `tkinter` module and allows you to reference it with
the alias `tk`.
- **`from tkinter import *`**: Imports all classes, functions, and constants from `tkinter` into
the current namespace. This means you can directly use widgets like `Button`, `Entry`, etc.,
without prefixing them with `tk.`.
Defining Attributes of the Main Window
root = tk.Tk()
root.geometry("170x230")
root.title("Calculator")
root.maxsize(170,230)
root.minsize(170,230)
- **`root = tk.Tk()`**: Creates the main application window (the root window).
- **`root.geometry('170x230')`**: Sets the size of the window to 170x230 pixels.
- **`root.title('Calculator')`**: Sets the title of the window to 'Calculator'.
- **`root.maxsize(170,230)`**: Sets the maximum size of the window to 170x230 pixels, so
the window can't be resized beyond these dimensions.
- **`root.minsize(170,230)`**: Sets the minimum size of the window to 170x230 pixels, so
the window can't be resized to a smaller size.
Entry Widget to Show Calculations
inp = Entry(root, width=16, borderwidth=3, relief=RIDGE)
inp.grid(pady=10, row=0, sticky="w", padx=15)
- **`inp = Entry(root, width=16, borderwidth=3, relief=RIDGE)`**: Creates an input field
(`Entry` widget) where users can enter the numbers and operations. - `width=16` specifies
the width of the entry.
- `borderwidth=3` gives the entry a border width of 3 pixels.
- `relief=RIDGE` gives the border a ridged look.
- **`inp.grid(pady=10, row=0, sticky='w', padx=15)`**: Places the `Entry` widget on the grid
at row 0. - `pady=10` adds padding along the Y-axis.
- `sticky='w'` aligns the widget to the west (left) side of the grid cell.
- `padx=15` adds padding along the X-axis.
Defining the Result Function
def result():
try:
if inp.get() == "":
inp.insert("end", "error")
elif inp.get()[0] == "0":
inp.delete(0, "end")
inp.insert("end", "error")
else:
res = inp.get()
res = eval(res)
inp.insert("end", " = ")
inp.insert("end", res)
except SyntaxError:
inp.insert("end", "invalid input")
- **`def result():`**: Defines a function called `result` that handles the evaluation of the
input.
- **`if inp.get() == '':`**: Checks if the input is empty.
- **`inp.insert('end', 'error')`**: If the input is empty, it inserts the word 'error' into the
`Entry` widget.
- **`elif inp.get()[0] == '0':`**: Checks if the first character of the input is '0'.
- **`inp.delete(0, 'end')`**: Deletes the entire content of the input if the first character is '0'.
- **`inp.insert('end', 'error')`**: Inserts the word 'error' after deleting the content.
- **`else:`**: If the input is not empty and doesn't start with '0':
- **`res = inp.get()`**: Gets the content of the `Entry` widget.
- **`res = eval(res)`**: Evaluates the expression in the `Entry` widget using Python's `eval`
function.
- **`inp.insert('end', ' = ')`**: Inserts the string ' = ' into the `Entry` widget.
- **`inp.insert('end', res)`**: Inserts the result of the evaluation into the `Entry` widget.
- **`except SyntaxError:`**: Catches any `SyntaxError` that occurs during the evaluation.
- **`inp.insert('end', 'invalid input')`**: Inserts the string 'invalid input' if there is a syntax
error.
Button Design Code
The next section of the code defines the buttons used in the calculator and places them on
the grid.
clear = Button(root, text="C", width=2, command=lambda: inp.delete(0, "end"), bg="red",
fg="white", relief=RIDGE)
clear.grid(row=0, sticky="w", padx=125)
- **`clear = Button(root, text='C', width=2, command=lambda: inp.delete(0, 'end'), bg='red',
fg='white', relief=RIDGE)`**: Creates a 'C' button to clear the input field.
- `text='C'` sets the button text to 'C'.
- `command=lambda: inp.delete(0, 'end')` sets the command to clear the input field when
the button is pressed.
- `bg='red'` sets the button background color to red.
- `fg='white'` sets the text color to white.
- `relief=RIDGE` gives the button a ridged border.
- **`clear.grid(row=0, sticky='w', padx=125)`**: Places the 'C' button on the grid at row 0.
The other buttons follow a similar pattern. Each button is associated with a lambda function
to insert the corresponding digit or operator into the `Entry` widget when pressed.
Mainloop to Run the Application
root.mainloop()
- **`root.mainloop()`**: Starts the Tkinter event loop, which waits for user interactions (like
button clicks) and keeps the application window open.
Summary
- **Entry Widget**: Provides an input field for the calculator.
- **Buttons**: Handle input operations and insert corresponding characters into the `Entry`
widget.
- **Result Function**: Evaluates the expression entered in the `Entry` widget and displays
the result.
- **Mainloop**: Keeps the application running and responsive.