Python

P
PythonHub
Progress 0%

Python

  • Home
  • History of Python
  • Applications of Python
  • Introduction To Python
    • What is Python
    • Character Set
    • Tokens in Python
    • Python Execution Mode
    • Variable And Identifiers
    • Data Types in Python
    • Operators And Expressions
    • Constants in Python
    • Assignment Statement
    • Input / Output in Python
    • Simple Python Scripts
    • Namespace in Python
    • 📝 Assignments
  • Operators in Python
    • Arithmetic Operators
    • Assignment Operators
    • Shorthand Assignment Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Special Operators
    • 📝 Assignments
  • Input Output in Python
    • Accept Input
    • Output Formatting
    • 📝 Assignments
  • Conditional Statement
    • Decision Making
    • if Statement
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • Short Hand IF-ELSE
    • 📝 Assignments
  • Loops
    • Introduction to Loops
    • While Loop
    • Nested While Loop
    • 📝 While Loop Assignments
    • For Loop
    • For Loop Examples
    • Nested For Loop
    • Nested For Loop Examples
    • Infinite While Loops
    • Infinite For Loops
    • Break, Continue and Else in Loops
    • Difference Between For and While Loop
    • For Each Loop
    • 📝 For Each Assignments
    • 📝 All Loops Assignments
  • List
    • List in Python
    • Access List Elements
    • List Functions
    • Iterate (Loop) List
    • List Comprehension
    • 📝 Assignments
  • Tuple
    • Tuple in Python
    • Access Tuple Elements
    • Tuple Functions
    • Iterate (Loop) Tuple
    • Unpack Tuple
    • Tuple Comprehension
    • 📝 Assignments
  • Set
    • Set in Python
    • Access Set Elements
    • Set Methods
    • Iterate (Loop) Set
    • Pack/Unpack Set
    • Set Comprehension
    • 📝 Assignments
  • Dictionary
    • Dictionary
    • Access Dictionary Items
    • Dictionary Methods
    • Iterate (Loop) Dictionary
    • Formatting Dictionaries
    • Nested Dictionaries
    • Dictionary Comprehension
    • 📝 Assignments
  • Diff List Tuple Set Dictionary
    • List vs Tuple
    • List vs Set
    • List vs Dictionary
    • Tuple vs Set
    • Tuple vs Dictionary
    • Dictionary vs Set
    • 📝 Assignments
  • Exception
    • Error vs Exception
    • Types of Exception
    • Exception Handling
    • User Defined Exception
    • Logging Exception
    • 📝 Assignments
  • Functions
    • Introduction to Functions
    • Modular Programming
    • Types of Functions
    • Inbuilt Functions
    • Need For User-Defined Function
    • Elements of User Defined Function
    • Function Arguments
    • Nesting of Functions
    • Recursion
    • Global Local and Non Local
    • Python Lambda Functions
    • 📝 Assignments
  • Python Module
    • Introduction to Module
    • Inbuilt Modules in Python
    • User Defined Module
    • 📝 Assignments
  • File Handling
    • Introduction to Files
    • Create File
    • Read Files
    • Write to File
    • Rename File
    • Copy File
    • Move File
    • List Files in Directory
    • Binary Files
    • Zipping and Unzipping Files
    • 📝 Assignments
  • Strings
    • Basics of Strings
    • String Special Operators
    • String Formatting Operators
    • String Methods
    • 📝 Assignments
  • Regular Expressions
  • Python OOPS
    • Basics of Object Oriented
    • What are Classes and Objects?
    • Creating Class and Object
    • OOP vs Procedural Programming
    • Difference Between Classes and Objects
    • Constructors
    • Destructor
    • Built Class Methods and Attributes
    • Class and Instance Variables
    • Inheritance in Python
    • Single Inheritance
    • Multiple Inheritance
    • Multilevel Inheritance
    • Hierarchical Inheritance
    • Hybrid Inheritance
    • Abstraction
    • Method Overriding
    • Abstract Method
    • Interfaces in Python
    • Abstract Class vs Interface
    • Public, Private and Protected
    • Overloading vs Overriding
    • Inheritance vs Composition
    • Encapsulation
    • Polymorphism
    • Inner Classes
    • 📝 Assignments
  • Advanced Python
    • Iterator in Python
    • Generator in Python
    • Decorator in Python
    • Type Hints in Python
    • Async/Await Programming
    • Dataclasses in Python
    • Context Managers in Python
    • Property Decorator in Python
    • __slots__ in Python
    • Enums in Python
    • Walrus Operator in Python
    • Match-Case in Python
    • 📝 Assignments
  • Python Standard Library
    • Collections Module
    • Itertools Module
    • Functools Module
    • Datetime Module
    • JSON Module
    • OS Module
    • Sys Module
    • Random Module
    • Math Module
    • 📝 Assignments
  • Python Testing
    • Unit Testing in Python
    • Pytest Framework
    • Mocking in Python
    • 📝 Assignments
  • Python Best Practices
    • PEP 8 Style Guide
    • Docstrings in Python
    • Logging in Python
    • Code Optimization Tips
    • Debugging Techniques
    • 📝 Assignments
  • MySQL Database in Python
    • Introduction to MySQL with Python
    • DBMS vs File System
    • Connecting to MySQL Database
    • Create Database in MySQL
    • Create Table in MySQL
    • Insert Data in MySQL
    • Insert Multiple Rows
    • Select Data from MySQL
    • WHERE Clause in MySQL
    • Update Data in MySQL
    • Delete Data from MySQL
    • Parameterized Queries
    • Transaction Management
    • Error Handling
    • Connection Pooling
    • MySQL Drivers Guide
    • Joins in MySQL
    • Aggregation Functions
    • Backup MySQL Database
    • Best Practices
    • 📝 Assignments
  • MySQL Database Operations
    • SELECT Statement
    • MySQL Operators
    • DDL Statements
    • DML Statements
    • Subqueries
    • JOIN Operations
    • Aggregation
    • Case Study
    • 📝 Assignments
  • Graphics in Python
  • Threads in Python
    • Introduction to Threads
    • Process vs Threads
    • Concurrent Programming & GIL
    • Uses of Threads
    • Creating Threads
    • Single Tasking
    • Multi Tasking
    • Thread Synchronization
    • 📝 Assignments
  • Interview Questions & Answers
  • Python Case Studies
  • Multiple Choice Questions
  • 📝 Practice Problems
Get in Touch
  • tech2dsm@gmail.com

© Sankalan Data Tech

Python Language Interactive Tutorial

Python: Graphics in Python

Python Graphics - Beginner's Guide

Learn how to create graphics in Python using Turtle, Matplotlib, and Tkinter.

Created by Sankalan Data Tech Team Verified
Data Engineers, Analysts, Scientists & Trainers
Created by experienced Python developers, data engineers, and data scientists to make programming easy through practical examples, real-world experience, and clear explanations.
Read Time: 12 minutes Level: Beginner Topic: Python Graphics
On this page:
  • What is Graphics in Python?
  • Turtle Graphics
  • Matplotlib for Charts
  • Tkinter Canvas
  • Which One to Choose?
  • Try It Yourself
  • Quiz
  • FAQ
Share this tutorial:
Twitter LinkedIn Facebook WhatsApp Reddit Telegram Email Copy Link
What You'll Learn Here
  • 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.

1

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

2

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

3

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

4

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?

5

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.

Loading Pyodide... 0%
Python Code Editor
========================================
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:

1. Which library is best for drawing shapes and patterns?
2. Which library is best for creating data charts?
3. What does turtle.forward(100) do?
4. Which Tkinter widget is used for drawing?
5. Which library comes built-in with Python?

Frequently Asked Questions

Do I need to install anything for Turtle graphics? ▼

No! Turtle is part of Python's standard library. You can start using it immediately with import turtle.

What is the best library for creating games in Python? ▼

For simple games, Tkinter Canvas works well. For more advanced games, consider Pygame which is specifically designed for game development.

What is a common interview question about Python graphics? ▼

Common questions include: "What libraries are available for graphics in Python?" "Explain the difference between Turtle and Matplotlib" and "How would you create a simple chart in Python?"

Can I create 3D graphics in Python? ▼

Yes! Libraries like PyOpenGL, VPython, and Mayavi allow you to create 3D graphics in Python. This tutorial focuses on 2D graphics for beginners.

What is the difference between Tkinter and Turtle? ▼

Turtle is specifically for drawing and is often used to teach programming concepts. Tkinter is a full GUI toolkit where Canvas is just one widget for drawing within a larger application.

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 →
Interview Resources
  • Python Syntax & Variables Interview Questions
  • Top SQL Interview Questions & Answers
  • SQL Joins: Displaying Data from Multiple Tables FAQ
Previous: MySQL Assignments Next: Threads Introduction →