- Turtle Graphics — drawing shapes and patterns
- Matplotlib — creating charts and plots
- Tkinter Canvas — building GUI applications
- When to use each — choosing the right tool
- Practical examples — real-world applications
What is Graphics in Python?
Graphics in Python refers to creating visual content — from simple shapes and drawings to complex charts and user interfaces. Python has several libraries that make graphics easy and fun.
Turtle Graphics
Draw shapes and patterns. Great for beginners and learning programming concepts.
Matplotlib
Create professional charts and graphs. Perfect for data visualization.
Tkinter Canvas
Build GUI applications with custom drawings. Good for interactive programs.
💡 Key concept: Python graphics libraries work by creating a window and drawing on it. Each library has its own way of doing this, but the basic idea is the same — you tell the computer where to draw and what to draw.
Installing Graphics Libraries
# ============================================================ # INSTALLING GRAPHICS LIBRARIES # ============================================================ # Turtle comes built-in with Python (no installation needed) # You can use it right away! # Matplotlib needs installation pip install matplotlib # Tkinter comes built-in with Python (no installation needed) # You can use it right away!
Key point: Turtle and Tkinter are built into Python. Matplotlib needs to be installed but is very popular for data visualization.
Quick Check: Which graphics library comes built-in with Python? (Answer: Turtle and Tkinter)
Turtle Graphics
Drawing with Turtle
Turtle graphics is like drawing with a robot that you control. You tell the turtle to move forward, turn, and draw. It's a great way to learn programming concepts.
# ============================================================
# TURTLE GRAPHICS EXAMPLES
# ============================================================
import turtle
# ============================================================
# 1. BASIC SHAPES
# ============================================================
# Create a turtle
t = turtle.Turtle()
# Draw a square
for i in range(4):
t.forward(100) # Move forward 100 pixels
t.right(90) # Turn right 90 degrees
# Draw a triangle
t.color("red") # Change color
t.forward(100)
t.right(120)
t.forward(100)
t.right(120)
t.forward(100)
# ============================================================
# 2. DRAWING A CIRCLE
# ============================================================
t.color("blue")
t.circle(50) # Draw a circle with radius 50
# ============================================================
# 3. DRAWING A SPIRAL
# ============================================================
t.color("green")
t.speed(0) # Fastest speed
for i in range(50):
t.forward(i * 2) # Move forward increasing distance
t.right(45) # Turn 45 degrees
# ============================================================
# 4. COLORFUL PATTERN
# ============================================================
colors = ["red", "orange", "yellow", "green", "blue", "purple"]
for i in range(36):
t.color(colors[i % 6])
t.forward(100)
t.right(60)
t.forward(50)
t.right(120)
t.forward(50)
t.right(60)
t.forward(100)
t.right(10)
# Keep the window open
turtle.done()
Turtle key points:
- forward(distance) — moves the turtle forward
- right(angle) — turns the turtle right
- left(angle) — turns the turtle left
- color(name) — changes the pen color
- circle(radius) — draws a circle
- speed(value) — controls drawing speed
Quick Check: What command moves the turtle forward? (Answer: forward(distance) or fd(distance))
Matplotlib for Charts
Creating Charts and Graphs
Matplotlib is the most popular library for creating charts and graphs in Python. It's widely used in data science and analytics.
# ============================================================
# MATPLOTLIB EXAMPLES
# ============================================================
import matplotlib.pyplot as plt
# ============================================================
# 1. LINE CHART
# ============================================================
# Data
x = [1, 2, 3, 4, 5]
y = [10, 15, 7, 12, 18]
plt.plot(x, y, marker='o', linestyle='-', color='blue')
plt.title("Sample Line Chart")
plt.xlabel("X Axis")
plt.ylabel("Y Axis")
plt.grid(True)
plt.show()
# ============================================================
# 2. BAR CHART
# ============================================================
categories = ['Apples', 'Bananas', 'Oranges', 'Grapes']
values = [25, 40, 30, 20]
plt.bar(categories, values, color=['red', 'yellow', 'orange', 'purple'])
plt.title("Fruit Sales")
plt.xlabel("Fruit")
plt.ylabel("Quantity Sold")
plt.show()
# ============================================================
# 3. PIE CHART
# ============================================================
sizes = [30, 25, 20, 15, 10]
labels = ['Python', 'Java', 'JavaScript', 'C++', 'Ruby']
colors = ['#ff9999', '#66b3ff', '#99ff99', '#ffcc99', '#c2c2f0']
plt.pie(sizes, labels=labels, colors=colors, autopct='%1.1f%%')
plt.title("Programming Language Popularity")
plt.show()
# ============================================================
# 4. SCATTER PLOT
# ============================================================
import random
x = [random.randint(1, 100) for _ in range(50)]
y = [random.randint(1, 100) for _ in range(50)]
plt.scatter(x, y, color='green', alpha=0.5)
plt.title("Scatter Plot")
plt.xlabel("X Values")
plt.ylabel("Y Values")
plt.show()
# ============================================================
# 5. MULTIPLE PLOTS
# ============================================================
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4))
# Line plot
ax1.plot([1, 2, 3, 4], [1, 4, 9, 16])
ax1.set_title("Line Plot")
# Bar plot
ax2.bar(['A', 'B', 'C', 'D'], [3, 7, 2, 5])
ax2.set_title("Bar Plot")
plt.show()
Matplotlib key points:
- plot() — line chart
- bar() — bar chart
- pie() — pie chart
- scatter() — scatter plot
- title() — chart title
- xlabel()/ylabel() — axis labels
- show() — display the chart
Quick Check: What function creates a bar chart in Matplotlib? (Answer: plt.bar())
Tkinter Canvas
Building GUI Applications with Canvas
Tkinter is Python's standard GUI library. The Canvas widget lets you draw shapes, images, and create interactive applications.
# ============================================================
# TKINTER CANVAS EXAMPLES
# ============================================================
import tkinter as tk
# ============================================================
# 1. BASIC WINDOW WITH CANVAS
# ============================================================
root = tk.Tk()
root.title("Tkinter Canvas")
canvas = tk.Canvas(root, width=400, height=300, bg='white')
canvas.pack()
# Draw a rectangle
canvas.create_rectangle(50, 50, 150, 100, fill='blue')
# Draw a circle (oval)
canvas.create_oval(200, 50, 300, 150, fill='red')
# Draw a line
canvas.create_line(50, 200, 350, 200, width=3, fill='green')
# Draw text
canvas.create_text(200, 250, text="Hello, Tkinter!", font=("Arial", 16))
root.mainloop()
# ============================================================
# 2. INTERACTIVE DRAWING
# ============================================================
class DrawingApp:
def __init__(self, root):
self.root = root
self.root.title("Drawing App")
self.canvas = tk.Canvas(root, width=500, height=400, bg='white')
self.canvas.pack()
# Bind mouse events
self.canvas.bind("", self.draw)
self.canvas.bind("", self.start_draw)
self.last_x = None
self.last_y = None
# Clear button
clear_btn = tk.Button(root, text="Clear", command=self.clear)
clear_btn.pack()
def start_draw(self, event):
self.last_x = event.x
self.last_y = event.y
def draw(self, event):
if self.last_x and self.last_y:
self.canvas.create_line(self.last_x, self.last_y, event.x, event.y,
width=3, fill='black', capstyle=tk.ROUND)
self.last_x = event.x
self.last_y = event.y
def clear(self):
self.canvas.delete("all")
app = DrawingApp(tk.Tk())
app.root.mainloop()
# ============================================================
# 3. ANIMATION EXAMPLE
# ============================================================
class AnimationApp:
def __init__(self, root):
self.root = root
self.root.title("Animation")
self.canvas = tk.Canvas(root, width=400, height=300, bg='white')
self.canvas.pack()
# Create a ball
self.ball = self.canvas.create_oval(50, 50, 70, 70, fill='red')
self.dx = 2
self.dy = 2
# Start animation
self.animate()
def animate(self):
# Move the ball
self.canvas.move(self.ball, self.dx, self.dy)
# Get ball position
x1, y1, x2, y2 = self.canvas.coords(self.ball)
# Bounce off walls
if x1 < 0 or x2 > 400:
self.dx = -self.dx
if y1 < 0 or y2 > 300:
self.dy = -self.dy
# Call again after 20ms
self.root.after(20, self.animate)
anim = AnimationApp(tk.Tk())
anim.root.mainloop()
Tkinter Canvas key points:
- create_rectangle() — draws a rectangle
- create_oval() — draws a circle or oval
- create_line() — draws a line
- create_text() — adds text
- move() — moves objects
- after() — creates animations
Quick Check: What method is used to move objects on the canvas? (Answer: canvas.move())
Which One to Choose?
Choosing the Right Graphics Library
# ============================================================
# LIBRARY COMPARISON
# ============================================================
print("""
┌─────────────────┬─────────────────────────────────────────────────────┐
│ Library │ Best Used For │
├─────────────────┼─────────────────────────────────────────────────────┤
│ Turtle │ - Learning programming concepts │
│ │ - Drawing simple shapes and patterns │
│ │ - Creating fun animations for kids │
│ │ - Teaching loops and functions │
├─────────────────┼─────────────────────────────────────────────────────┤
│ Matplotlib │ - Data visualization │
│ │ - Creating charts and graphs │
│ │ - Scientific plotting │
│ │ - Business reports and dashboards │
├─────────────────┼─────────────────────────────────────────────────────┤
│ Tkinter Canvas │ - Building GUI applications │
│ │ - Interactive drawing tools │
│ │ - Games and animations │
│ │ - Custom user interfaces │
└─────────────────┴─────────────────────────────────────────────────────┘
# ============================================================
# RECOMMENDATIONS
# ============================================================
print("""
1. If you're a beginner learning programming → Use Turtle
2. If you need to visualize data → Use Matplotlib
3. If you're building a desktop application → Use Tkinter
4. If you want to make games → Tkinter or Pygame (not covered here)
5. If you want to create interactive web graphics → Consider Plotly or D3.js
""")
Summary:
- Turtle — learning and fun drawings
- Matplotlib — data visualization
- Tkinter Canvas — GUI applications
Quick Check: Which library is best for creating data charts? (Answer: Matplotlib)
Try It Yourself
Experiment with graphics in the editor below.
GRAPHICS IN PYTHON - PRACTICE
========================================
1. TURTLE SIMULATION - DRAWING A SQUARE
----------------------------------------
Drawing a square:
Moving 100 pixels forward
New position: (100.0, 0.0)
Turning right 90 degrees
Moving 100 pixels forward
New position: (100.0, -100.0)
Turning right 90 degrees
Moving 100 pixels forward
New position: (0.0, -100.0)
Turning right 90 degrees
Moving 100 pixels forward
New position: (0.0, 0.0)
Turning right 90 degrees
2. TURTLE SIMULATION - DRAWING A SPIRAL
----------------------------------------
Changing color to green
Drawing a spiral:
Moving 0 pixels forward
New position: (0.0, 0.0)
Turning right 45 degrees
Moving 10 pixels forward
New position: (7.1, -7.1)
Turning right 45 degrees
... (continues for 10 iterations)
3. GRAPHICS LIBRARY COMPARISON
----------------------------------------
┌─────────────────┬─────────────────────────────────────────────────────┐
│ Library │ When to Use │
├─────────────────┼─────────────────────────────────────────────────────┤
│ Turtle │ Learning programming, simple drawings │
│ Matplotlib │ Charts, data visualization │
│ Tkinter Canvas │ GUI applications, interactive drawing │
└─────────────────┴─────────────────────────────────────────────────────┘
4. BASIC SHAPES IN PYTHON GRAPHICS
----------------------------------------
Common shapes you can draw:
- Square: 4 sides, 90 degree angles
- Circle: 360 degree rotation
- Triangle: 3 sides, 120 degree angles
- Star: 5 points, 144 degree angles
- Spiral: Increasing radius with rotation
5. QUICK START GUIDE
----------------------------------------
To start with graphics:
1. Turtle: import turtle
2. Matplotlib: import matplotlib.pyplot as plt
3. Tkinter: import tkinter as tk
All libraries are well-documented and have many examples online.
Start with simple shapes and gradually build complexity!
Graphics in Python is fun and creative!
You've Got It!
You now understand graphics in Python. You know Turtle for drawing, Matplotlib for charts, and Tkinter Canvas for GUI applications.
Quick Quiz
Test what you've learned:
Frequently Asked Questions
Do I need to install anything for Turtle graphics?
import turtle.
What is the best library for creating games in Python?
What is a common interview question about Python graphics?
Can I create 3D graphics in Python?
What is the difference between Tkinter and Turtle?
Where to Go From Here
Now that you understand graphics in Python, check out these related topics:
Threads in Python
Learn about concurrent programming.
Learn More →MySQL with Python
Learn how to connect Python to MySQL.
Learn More →Regular Expressions
Learn pattern matching in Python.
Learn More →