Matplotlib
Matplotlib is a plotting library used to create graphs and visualizations in Python.
Basic functions:
- plot() - Creates line graphs (x vs y plots)
- scatter() - Makes dot/scatter plots
- bar() - Creates bar charts
- xlabel()/ylabel() - Labels for x and y axes
- title() - Adds title to the graph
- show() - Displays the graph
Example Program:
import matplotlib.pyplot as plt x = [1, 2, 3, 4] y = [10, 20, 25, 30] plt.plot(x, y) plt.xlabel('X-axis') plt.ylabel('Y-axis') plt.title('Simple Plot') plt.show()
NumPy
NumPy is used for numerical computing in Python. It provides powerful array objects.
Basic functions:
- array() - Creates NumPy arrays
- linspace() - Creates evenly spaced numbers
- zeros()/ones() - Arrays filled with 0s or 1s
- arange() - Similar to range() but returns array
- reshape() - Changes array shape
- dot() - Matrix multiplication
Example Program:
import numpy as np arr = np.array([1, 2, 3, 4]) print("Array:", arr) print("Square of array:", arr**2) matrix = np.array([[1, 2], [3, 4]]) print("Matrix multiplication:", np.dot(matrix, matrix))
Pandas
Pandas is used for data manipulation and analysis, especially with tables.
Basic functions:
- DataFrame() - Creates a table-like structure
- read_csv() - Reads data from CSV files
- head() - Shows first few rows
- describe() - Shows statistics of data
- groupby() - Groups data by categories
- plot() - Creates plots from data
Example Program:
import pandas as pd data = {'Name': ['John', 'Anna', 'Peter'], 'Age': [25, 30, 22]} df = pd.DataFrame(data) print("DataFrame:") print(df) print("\nAverage age:", df['Age'].mean())
Combining Packages
These packages often work together:
import numpy as np import matplotlib.pyplot as plt import pandas as pd # Create data using NumPy x = np.linspace(0, 10, 100) y = np.sin(x) # Plot using Matplotlib plt.plot(x, y) plt.title('Sine Wave') plt.show() # Use Pandas for data analysis data = pd.DataFrame({'x': x, 'sin(x)': y}) print(data.describe())
Key Points to Remember:
- - Matplotlib is for plotting and visualization
- - NumPy handles numerical operations and arrays
- - Pandas is for data manipulation and analysis
- - These packages are often used together
- - Always import the packages before using them
- - Many functions have similar names across packages but different uses
GUI Programming
GUI stands for Graphical User Interface. It allows users to interact with programs using visual elements like buttons, windows, and menus instead of typing commands.
Introduction to Tkinter
Tkinter is Python's standard package for creating GUI applications. It's:
- - Built into Python (no extra installation needed)
- - Simple to use for basic applications
- - Cross-platform (works on Windows, Mac, Linux)
- - Based on the Tk GUI toolkit
Basic Tkinter Components
Main Window: The base window where all other elements are placed
Widgets: The building blocks of GUI applications:
- Label - Displays text or images
- Button - Clickable button that performs actions
- Entry - Single-line text input field
- Text - Multi-line text area
- Checkbutton - On/off toggle button
- Radiobutton - Select one from multiple options
- Frame - Container to organize other widgets
Basic Tkinter Program Structure
# Import the Tkinter module from tkinter import * # 1. Create main window root = Tk() # 2. Add widgets label = Label(root, text="Hello World!") button = Button(root, text="Click Me") # 3. Arrange widgets using geometry managers label.pack() button.pack() # 4. Start the main event loop root.mainloop()
Important Tkinter Concepts
Geometry Managers:
- pack() - Simple automatic positioning
- grid() - Places widgets in table-like rows and columns
- place() - Precise positioning with x,y coordinates
Event Handling:
def button_click(): print("Button was clicked!") button = Button(root, text="Click", command=button_click)
Complete Example Program
from tkinter import * def calculate(): num1 = float(entry1.get()) num2 = float(entry2.get()) result = num1 + num2 result_label.config(text=f"Result: {result}") # Create main window root = Tk() root.title("Simple Calculator") # Create widgets Label(root, text="First Number:").grid(row=0, column=0) entry1 = Entry(root) entry1.grid(row=0, column=1) Label(root, text="Second Number:").grid(row=1, column=0) entry2 = Entry(root) entry2.grid(row=1, column=1) Button(root, text="Add", command=calculate).grid(row=2, column=0, columnspan=2) result_label = Label(root, text="Result: ") result_label.grid(row=3, column=0, columnspan=2) # Start the application root.mainloop()
Key Points to Remember
- - Always import Tkinter first (from tkinter import *)
- - Create the main window with Tk()
- - All widgets must be placed using pack(), grid(), or place()
- - Use mainloop() to start the application
- - Event handlers are normal Python functions
- - Widgets can be customized with various options (text, color, size etc.)
- - Tkinter is simple but powerful enough for many applications
Advantages of Tkinter
- - Comes with Python (no extra installation)
- - Good for simple to medium complexity GUIs
- - Large community and documentation
- - Cross-platform (works everywhere Python works)
Tkinter Widgets
Widgets are the building blocks of Tkinter applications. Here are the most important ones:
Basic Widgets:
- Label - Displays text or image
Label(root, text="Hello World")
- Button - Clickable button that performs action
Button(root, text="Click", command=function)
- Entry - Single line text input
Entry(root, width=30)
- Text - Multi-line text area
Text(root, height=5, width=30)
Selection Widgets:
- Checkbutton - On/off toggle
Checkbutton(root, text="Option 1", variable=var1)
- Radiobutton - Select one from many
Radiobutton(root, text="Male", variable=var, value=1)
- Listbox - List of selectable items
Listbox(root, height=4)
Container Widgets:
- Frame - Groups other widgets
Frame(root, bg="lightgray")
- Canvas - For drawing graphics
Canvas(root, width=200, height=100)
Tkinter Examples
Example 1: Simple Form
from tkinter import * def submit(): print(f"Name: {name_entry.get()}") print(f"Age: {age_entry.get()}") root = Tk() Label(root, text="Name:").grid(row=0, column=0) name_entry = Entry(root) name_entry.grid(row=0, column=1) Label(root, text="Age:").grid(row=1, column=0) age_entry = Entry(root) age_entry.grid(row=1, column=1) Button(root, text="Submit", command=submit).grid(row=2, columnspan=2) root.mainloop()
Example 2: Temperature Converter
from tkinter import * def convert(): celsius = float(entry.get()) fahrenheit = (celsius * 9/5) + 32 result_label.config(text=f"{fahrenheit:.2f}°F") root = Tk() root.title("Temperature Converter") Label(root, text="Celsius:").pack() entry = Entry(root) entry.pack() Button(root, text="Convert", command=convert).pack() result_label = Label(root, text="") result_label.pack() root.mainloop()
Python Programming with IDE
What is an IDE?
IDE (Integrated Development Environment) is software that helps write, test and debug programs.
Popular Python IDEs:
- IDLE - Comes with Python, simple for beginners
- PyCharm - Professional IDE with many features
- VS Code - Lightweight but powerful with extensions
- Spyder - Good for scientific computing
- Jupyter Notebook - Web-based for data science
IDE Features for Tkinter:
- - Code completion (suggests widget names and options)
- - Syntax highlighting (colors different parts of code)
- - Debugger (helps find and fix errors)
- - GUI preview (some IDEs show how GUI will look)
No comments:
Post a Comment