2025年7月1日火曜日

How to draw in python , which modules are used

Drawing in Python can be done using several modules, each with its own strengths and use cases.1 Here are some of the most commonly used ones:

1. matplotlib

  • What it is: matplotlib is a comprehensive library for creating static, animated, and interactive visualizations in Python.2 While often associated with plotting data (line plots, bar charts, scatter plots), it's also capable of drawing basic shapes and even complex custom figures.3

  • Use Cases:

    • Data Visualization: This is its primary strength.

    • Basic Shapes: Drawing lines, rectangles, circles, polygons.4

    • Custom Graphics: Creating diagrams, illustrations, and more artistic representations.

    • Saving Plots: Can save figures in various formats (PNG, JPG, PDF, SVG).5

  • Drawing Approach: You typically create a figure and an axes object, then use methods like plot() for lines, add_patch() for shapes (e.g., Rectangle, Circle, Polygon), or imshow() for images.

  • Example (Basic Line Drawing):

    Python
    import matplotlib.pyplot as plt
    
    # Create a figure and an axes object
    fig, ax = plt.subplots()
    
    # Draw a line from (0,0) to (1,1)
    ax.plot([0, 1], [0, 1], color='blue', linewidth=2)
    
    # Draw another line
    ax.plot([0, 1], [1, 0], color='red', linestyle='--')
    
    # Set limits and aspect ratio (optional)
    ax.set_xlim(-0.5, 1.5)
    ax.set_ylim(-0.5, 1.5)
    ax.set_aspect('equal', adjustable='box') # Make sure units are square
    
    plt.title("Simple Line Drawing with Matplotlib")
    plt.xlabel("X-axis")
    plt.ylabel("Y-axis")
    plt.grid(True)
    plt.show()
    

2. Pillow (PIL - Python Imaging Library Fork)

  • What it is: Pillow is a powerful image processing library.6 While not primarily a "drawing" library in the sense of creating vector graphics from scratch, it provides excellent tools for drawing directly onto raster images (like JPEGs or PNGs).

  • Use Cases:

    • Image Manipulation: Resizing, cropping, rotating, applying filters.7

    • Adding Text to Images: Watermarking, captions.8

    • Drawing Shapes on Images: Drawing lines, rectangles, circles, ellipses, polygons directly onto an existing image or a newly created blank image.

    • Creating Simple Images Programmatically: Generating simple images with specific colors and shapes.

  • Drawing Approach: You create an Image object (either by loading an existing image or creating a new blank one) and then create an ImageDraw object from it.9 The ImageDraw object provides methods like line(), rectangle(), ellipse(), text(), etc.

  • Example (Drawing on an Image):

    Python
    from PIL import Image, ImageDraw
    
    # Create a new blank image (e.g., white background)
    img = Image.new('RGB', (400, 300), color = 'white')
    draw = ImageDraw.Draw(img)
    
    # Draw a red rectangle
    draw.rectangle((50, 50, 150, 150), fill='red', outline='black')
    
    # Draw a blue circle
    draw.ellipse((200, 50, 300, 150), fill='blue', outline='darkblue')
    
    # Draw a green line
    draw.line((50, 200, 350, 250), fill='green', width=5)
    
    # Add some text
    draw.text((10, 10), "Hello, Pillow!", fill='black')
    
    # Save or show the image
    img.save("drawing_with_pillow.png")
    # img.show() # Uncomment to display the image directly
    print("Image saved as drawing_with_pillow.png")
    

3. Tkinter (built-in)

  • What it is: Tkinter is Python's standard GUI (Graphical User Interface) toolkit. It comes built-in with Python, so you don't need to install anything extra. It includes a Canvas widget that is specifically designed for drawing.10

  • Use Cases:

    • Simple GUI Applications: Creating windows, buttons, text fields.

    • Interactive Drawing Applications: Building drawing programs where users can interact with shapes.11

    • Creating Simple Animations: Moving shapes on the canvas.

  • Drawing Approach: You create a Tkinter window, add a Canvas widget to it, and then use the canvas's methods like create_line(), create_rectangle(), create_oval(), create_polygon(), create_text(), etc.

  • Example (Tkinter Canvas):

    Python
    import tkinter as tk
    
    root = tk.Tk()
    root.title("Tkinter Drawing")
    
    canvas = tk.Canvas(root, width=400, height=300, bg="lightgray")
    canvas.pack()
    
    # Draw a red rectangle
    canvas.create_rectangle(50, 50, 150, 150, fill="red", outline="black")
    
    # Draw a blue circle (oval)
    canvas.create_oval(200, 50, 300, 150, fill="blue", outline="darkblue")
    
    # Draw a green line
    canvas.create_line(50, 200, 350, 250, fill="green", width=5)
    
    # Add some text
    canvas.create_text(10, 10, anchor="nw", text="Hello, Tkinter!", fill="black")
    
    root.mainloop()
    

4. Pygame

  • What it is: Pygame is a set of Python modules designed for writing video games. It provides functionalities for graphics, sound, and user input. While geared towards games, its drawing capabilities are excellent for general-purpose graphics.

  • Use Cases:

    • Game Development: Its primary purpose.

    • Interactive Simulations: Creating visual simulations.12

    • Real-time Graphics: Applications requiring dynamic and responsive drawing.

    • Animations: Creating animated sequences.13

  • Drawing Approach: You initialize Pygame, create a display surface (your window), and then use functions from pygame.draw (e.g., pygame.draw.line(), pygame.draw.rect(), pygame.draw.circle()) to draw onto that surface. You then update the display to show what you've drawn.

  • Example (Pygame):

    Python
    import pygame
    
    # Initialize Pygame
    pygame.init()
    
    # Set up the display (window)
    screen_width = 600
    screen_height = 400
    screen = pygame.display.set_mode((screen_width, screen_height))
    pygame.display.set_caption("Pygame Drawing")
    
    # Define colors
    WHITE = (255, 255, 255)
    RED = (255, 0, 0)
    BLUE = (0, 0, 255)
    GREEN = (0, 255, 0)
    BLACK = (0, 0, 0)
    
    running = True
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
    
        # Fill the background
        screen.fill(WHITE)
    
        # Draw a red rectangle
        pygame.draw.rect(screen, RED, (50, 50, 100, 100)) # (x, y, width, height)
    
        # Draw a blue circle
        pygame.draw.circle(screen, BLUE, (300, 100), 50) # (center_x, center_y), radius
    
        # Draw a green line
        pygame.draw.line(screen, GREEN, (50, 200), (550, 300), 5) # (start_x, start_y), (end_x, end_y), width
    
        # Draw some text (requires font setup)
        font = pygame.font.Font(None, 36) # Default font, size 36
        text_surface = font.render("Hello, Pygame!", True, BLACK) # Text, Antialias, Color
        screen.blit(text_surface, (10, 10))
    
        # Update the display
        pygame.display.flip()
    
    pygame.quit()
    

5. Turtle (built-in)

  • What it is: The turtle module is an introductory graphics module that provides a simple way to draw using a "turtle" cursor that moves around on a canvas. It's excellent for learning programming concepts and creating geometric patterns.

  • Use Cases:

    • Educational Tool: Ideal for teaching programming fundamentals.

    • Geometric Art: Drawing fractals, spirals, and other mathematical patterns.14

    • Simple Animations: Moving the turtle to create paths.15

  • Drawing Approach: You control a turtle object by telling it to move forward, turn, lift its pen, put its pen down, change color, etc.16

  • Example (Turtle Graphics):

    Python
    import turtle
    
    # Create a turtle screen
    screen = turtle.Screen()
    screen.setup(width=600, height=400)
    screen.bgcolor("lightblue")
    screen.title("Turtle Drawing")
    
    # Create a turtle object
    pen = turtle.Turtle()
    pen.speed(0) # Fastest speed
    
    # Draw a square
    pen.color("red")
    for _ in range(4):
        pen.forward(100)
        pen.left(90)
    
    # Move to a new position
    pen.penup()
    pen.goto(-150, 0)
    pen.pendown()
    
    # Draw a star
    pen.color("blue")
    for _ in range(5):
        pen.forward(100)
        pen.right(144)
    
    # Keep the window open until closed manually
    screen.exitonclick()
    

Other Notable Modules (More Specialized):

  • Cairo (pycairo): A Python binding to the Cairo graphics library. It's a 2D graphics library that supports multiple output devices.17 It's powerful for high-quality vector graphics but has a steeper learning curve than some others.

  • SVGWrite: A module for generating SVG (Scalable Vector Graphics) files programmatically. Great if your output needs to be vector-based and scalable.

  • PIL.ImageDraw (as part of Pillow):18 As mentioned above, it's the specific module within Pillow used for drawing.

  • ReportLab: A powerful library for creating PDF documents programmatically, which includes extensive drawing capabilities for charts, shapes, and text layout.

Choosing the Right Module:

The best module for you depends on your specific needs:

  • For Data Visualization: matplotlib is the go-to.19

  • For Image Manipulation and Drawing on Rasters: Pillow.

  • For Simple GUI applications with drawing features: Tkinter.

  • For Game Development or Real-time Interactive Graphics: Pygame.

  • For Learning and Geometric Patterns: Turtle.

  • For High-Quality Vector Graphics / PDF generation: Pycairo, SVGWrite, ReportLab.

You might also find that for more complex or 3D graphics, modules like Pyglet, ArcGIS API for Python (for GIS), or even bindings to OpenGL (e.g., PyOpenGL) come into play, but for general "drawing" in 2D, the ones listed above are the most common starting points.