
- Python - Home
- Python - Overview
- Python - History
- Python - Features
- Python vs C++
- Python - Hello World Program
- Python - Application Areas
- Python - Interpreter
- Python - Environment Setup
- Python - Virtual Environment
- Python - Basic Syntax
- Python - Variables
- Python - Data Types
- Python - Type Casting
- Python - Unicode System
- Python - Literals
- Python - Operators
- Python - Arithmetic Operators
- Python - Comparison Operators
- Python - Assignment Operators
- Python - Logical Operators
- Python - Bitwise Operators
- Python - Membership Operators
- Python - Identity Operators
- Python - Operator Precedence
- Python - Comments
- Python - User Input
- Python - Numbers
- Python - Booleans
- Python - Control Flow
- Python - Decision Making
- Python - If Statement
- Python - If else
- Python - Nested If
- Python - Match-Case Statement
- Python - Loops
- Python - for Loops
- Python - for-else Loops
- Python - While Loops
- Python - break Statement
- Python - continue Statement
- Python - pass Statement
- Python - Nested Loops
- Python Functions & Modules
- Python - Functions
- Python - Default Arguments
- Python - Keyword Arguments
- Python - Keyword-Only Arguments
- Python - Positional Arguments
- Python - Positional-Only Arguments
- Python - Arbitrary Arguments
- Python - Variables Scope
- Python - Function Annotations
- Python - Modules
- Python - Built in Functions
- Python Strings
- Python - Strings
- Python - Slicing Strings
- Python - Modify Strings
- Python - String Concatenation
- Python - String Formatting
- Python - Escape Characters
- Python - String Methods
- Python - String Exercises
- Python Lists
- Python - Lists
- Python - Access List Items
- Python - Change List Items
- Python - Add List Items
- Python - Remove List Items
- Python - Loop Lists
- Python - List Comprehension
- Python - Sort Lists
- Python - Copy Lists
- Python - Join Lists
- Python - List Methods
- Python - List Exercises
- Python Tuples
- Python - Tuples
- Python - Access Tuple Items
- Python - Update Tuples
- Python - Unpack Tuples
- Python - Loop Tuples
- Python - Join Tuples
- Python - Tuple Methods
- Python - Tuple Exercises
- Python Sets
- Python - Sets
- Python - Access Set Items
- Python - Add Set Items
- Python - Remove Set Items
- Python - Loop Sets
- Python - Join Sets
- Python - Copy Sets
- Python - Set Operators
- Python - Set Methods
- Python - Set Exercises
- Python Dictionaries
- Python - Dictionaries
- Python - Access Dictionary Items
- Python - Change Dictionary Items
- Python - Add Dictionary Items
- Python - Remove Dictionary Items
- Python - Dictionary View Objects
- Python - Loop Dictionaries
- Python - Copy Dictionaries
- Python - Nested Dictionaries
- Python - Dictionary Methods
- Python - Dictionary Exercises
- Python Arrays
- Python - Arrays
- Python - Access Array Items
- Python - Add Array Items
- Python - Remove Array Items
- Python - Loop Arrays
- Python - Copy Arrays
- Python - Reverse Arrays
- Python - Sort Arrays
- Python - Join Arrays
- Python - Array Methods
- Python - Array Exercises
- Python File Handling
- Python - File Handling
- Python - Write to File
- Python - Read Files
- Python - Renaming and Deleting Files
- Python - Directories
- Python - File Methods
- Python - OS File/Directory Methods
- Python - OS Path Methods
- Object Oriented Programming
- Python - OOPs Concepts
- Python - Classes & Objects
- Python - Class Attributes
- Python - Class Methods
- Python - Static Methods
- Python - Constructors
- Python - Access Modifiers
- Python - Inheritance
- Python - Polymorphism
- Python - Method Overriding
- Python - Method Overloading
- Python - Dynamic Binding
- Python - Dynamic Typing
- Python - Abstraction
- Python - Encapsulation
- Python - Interfaces
- Python - Packages
- Python - Inner Classes
- Python - Anonymous Class and Objects
- Python - Singleton Class
- Python - Wrapper Classes
- Python - Enums
- Python - Reflection
- Python Errors & Exceptions
- Python - Syntax Errors
- Python - Exceptions
- Python - try-except Block
- Python - try-finally Block
- Python - Raising Exceptions
- Python - Exception Chaining
- Python - Nested try Block
- Python - User-defined Exception
- Python - Logging
- Python - Assertions
- Python - Built-in Exceptions
- Python Multithreading
- Python - Multithreading
- Python - Thread Life Cycle
- Python - Creating a Thread
- Python - Starting a Thread
- Python - Joining Threads
- Python - Naming Thread
- Python - Thread Scheduling
- Python - Thread Pools
- Python - Main Thread
- Python - Thread Priority
- Python - Daemon Threads
- Python - Synchronizing Threads
- Python Synchronization
- Python - Inter-thread Communication
- Python - Thread Deadlock
- Python - Interrupting a Thread
- Python Networking
- Python - Networking
- Python - Socket Programming
- Python - URL Processing
- Python - Generics
- Python Libraries
- NumPy Tutorial
- Pandas Tutorial
- SciPy Tutorial
- Matplotlib Tutorial
- Django Tutorial
- OpenCV Tutorial
- Python Miscellenous
- Python - Date & Time
- Python - Maths
- Python - Iterators
- Python - Generators
- Python - Closures
- Python - Decorators
- Python - Recursion
- Python - Reg Expressions
- Python - PIP
- Python - Database Access
- Python - Weak References
- Python - Serialization
- Python - Templating
- Python - Output Formatting
- Python - Performance Measurement
- Python - Data Compression
- Python - CGI Programming
- Python - XML Processing
- Python - GUI Programming
- Python - Command-Line Arguments
- Python - Docstrings
- Python - JSON
- Python - Sending Email
- Python - Further Extensions
- Python - Tools/Utilities
- Python - GUIs
- Python Advanced Concepts
- Python - Abstract Base Classes
- Python - Custom Exceptions
- Python - Higher Order Functions
- Python - Object Internals
- Python - Memory Management
- Python - Metaclasses
- Python - Metaprogramming with Metaclasses
- Python - Mocking and Stubbing
- Python - Monkey Patching
- Python - Signal Handling
- Python - Type Hints
- Python - Automation Tutorial
- Python - Humanize Package
- Python - Context Managers
- Python - Coroutines
- Python - Descriptors
- Python - Diagnosing and Fixing Memory Leaks
- Python - Immutable Data Structures
- Python Useful Resources
- Python - Questions & Answers
- Python - Interview Questions & Answers
- Python - Online Quiz
- Python - Quick Guide
- Python - Reference
- Python - Cheatsheet
- Python - Projects
- Python - Useful Resources
- Python - Discussion
- Python Compiler
- NumPy Compiler
- Matplotlib Compiler
- SciPy Compiler
Create MS Paint Clone with Python and PyGame
It is a python script that enables the users to draw on the screen through the Pygame library. It records mouse events to enable you draw on it and each new draw may be of a random color and the brush size is also selectable. In the script the main ideas of block-based programming, such as event handling, drawing, and the utilization of the concept of randomness to control visuals are illustrated clearly and without unnecessary complexity.
Required Libraries
To run this script, you need to install the following library −
Pygame
This library is applied for the development of video games and graphical interface in Python. It deals within managing the windows and capturing the inputs from the user and even drawing things on the screen.
Go to your terminal and run this code −
pip install pygame
Steps to Create MS Paint Clone
Step 1: Importing Necessary Modules
You need to import the pygame − It provides the necessary functionality for creating the drawing interface
And, random − It is used to generate random colors for each new drawing stroke.
import pygame, random
Step 2: Initialize Pygame
To initialize pygame, use the init() method. The following code statement is used to initialize the pygame −
pygame.init()
Step 3: Setting Up the Display
Use the following code statements to create a window of size 1024x768 pixels where the drawing will occur −
screen = pygame.display.set_mode((1024, 768))
Step 4: Initializing Drawing Settings
To initialize drawing settings, use the following variables −
- draw_on − A boolean flag that tracks whether the mouse button is held down.
- last_pos − Keeps track of the last mouse position to draw continuous lines
- color − Initial brush color, set to a shade of blue.
- radius − Size of the brush, set to 15 pixels.
The following code statements are initializing drawing settings −
draw_on = False last_pos = (0, 0) color = (0, 128, 255) radius = 15
Step 5: Defining the Round Line Function
Here is the code for defining the round line function −
def roundline(srf, color, start, end, radius=1): dx = end[0] - start[0] dy = end[1] - start[1] distance = max(abs(dx), abs(dy)) for i in range(distance): x = int(start[0] + float(i) / distance * dx) y = int(start[1] + float(i) / distance * dy) pygame.draw.circle(srf, color, (x, y), radius)
Step 6: Handling the Quit Event
To handle the quit event, use the following code −
e = pygame.event.wait() if e.type == pygame.QUIT: raise StopIteration
Step 7: Handling Mouse Button Down
To handle mouse button down event, use the following code −
if e.type == pygame.MOUSEBUTTONDOWN: color = (random.randrange(100, 256), random.randrange(100, 256), random.randrange(100, 256)) pygame.draw.circle(screen, color, e.pos, radius) draw_on = True
Step 8: Handling Script Termination
Use the following code to handle script termination −
except StopIteration: pass pygame.quit()
Code to Create MS Paint Clone with Python and PyGame
import pygame, random # Initialize Pygame pygame.init() # Set up the display screen = pygame.display.set_mode((1024, 768)) # Changed resolution to 1024x768 # Initialize drawing settings draw_on = False last_pos = (0, 0) color = (0, 128, 255) # Changed initial color to a blue shade radius = 15 # Increased the brush size to 15 def roundline(srf, color, start, end, radius=1): dx = end[0] - start[0] dy = end[1] - start[1] distance = max(abs(dx), abs(dy)) for i in range(distance): x = int(start[0] + float(i) / distance * dx) y = int(start[1] + float(i) / distance * dy) pygame.draw.circle(srf, color, (x, y), radius) try: while True: e = pygame.event.wait() if e.type == pygame.QUIT: raise StopIteration if e.type == pygame.MOUSEBUTTONDOWN: color = (random.randrange(100, 256), random.randrange(100, 256), random.randrange(100, 256)) # Restricted color range to brighter colors pygame.draw.circle(screen, color, e.pos, radius) draw_on = True if e.type == pygame.MOUSEBUTTONUP: draw_on = False if e.type == pygame.MOUSEMOTION: if draw_on: pygame.draw.circle(screen, color, e.pos, radius) roundline(screen, color, e.pos, last_pos, radius) last_pos = e.pos pygame.display.flip() except StopIteration: pass pygame.quit()
OUTPUT
When you execute this script a window will be created with background color white and nothing else. When you use the mouse to click and drag, paths in the colors appear as if they are virtually trailing the cursor. Every time you set off a new brush stroke, the colour selected from within the bright spectrum will be different from the previous one and so you actively drawing.

Use your right click button in your mouse, you can also draw like this.
Code Explanation
- The script starts from the importing of some modules for graphics and input control − Pygame; for random color creation − random.
- It only starts Pygame and opens the drawing window with the desired resolution.
- First, the aspect of the drawing is set like color selection and size of the brush used to draw.
- A helper function roundline is made to make the line drawn more smooth whenever needed.
- The idea of the main loop is to deal with different incidents such as mouse clicks and movements and draw on the canvas.
Still, the display to which the drawing is drawn is update frequently to reflect the drawing in real-time.
- The script also stops running when the user closes the window, thus no abrupt actions are implemented in the termination of the script.
- With every new mouse click, it gives off new colors making this a fun drawing tool.
- The drawing is interactivity based on movements of the cursor with the help of the continuous event handling.
- Last, the script exits Pygame, which also closes the window in which Shapes was being drawn.
- Although very fundamental − this script provides a good example of accepting user input, as well as drawing graphical images using Python and Pygame.