How to make a Tkinter canvas rectangle transparent?

The Canvas widget in Tkinter is versatile for drawing shapes and graphics. By default, Tkinter doesn't support transparency (alpha) for canvas shapes. However, we can create transparent rectangles by combining PIL (Python Imaging Library) with Tkinter's image capabilities.

Understanding the Approach

To create transparent rectangles, we need to ?

  • Create a custom function that accepts an alpha parameter
  • Use PIL to create an RGBA image with transparency
  • Convert the PIL image to a PhotoImage for Tkinter
  • Display the transparent image on the canvas

Creating Transparent Rectangles

Here's a complete example that creates multiple transparent rectangles ?

import tkinter as tk
from PIL import Image, ImageTk

# Create main window
root = tk.Tk()
root.title("Transparent Canvas Rectangles")
root.geometry("700x400")

# Store images to prevent garbage collection
images = []

def create_transparent_rectangle(canvas, x, y, width, height, fill_color, alpha):
    """Create a transparent rectangle on canvas"""
    # Convert color name to RGB values
    rgb_color = root.winfo_rgb(fill_color)
    # Normalize RGB values (0-65535) to (0-255) and add alpha
    normalized_color = tuple(int(c/256) for c in rgb_color) + (int(alpha * 255),)
    
    # Create transparent image
    image = Image.new('RGBA', (width, height), normalized_color)
    photo = ImageTk.PhotoImage(image)
    
    # Store reference to prevent garbage collection
    images.append(photo)
    
    # Place image on canvas
    canvas.create_image(x, y, image=photo, anchor='nw')

# Create canvas
canvas = tk.Canvas(root, bg='white')
canvas.pack(fill='both', expand=True)

# Create transparent rectangles with different colors and transparency levels
create_transparent_rectangle(canvas, 50, 50, 200, 100, 'blue', 0.3)
create_transparent_rectangle(canvas, 100, 80, 200, 100, 'red', 0.5)
create_transparent_rectangle(canvas, 150, 110, 200, 100, 'green', 0.2)

root.mainloop()
A window will display with three overlapping transparent rectangles in blue, red, and green colors with different transparency levels.

Advanced Example with Custom Function

Here's an enhanced version that mimics Tkinter's native create_rectangle method ?

import tkinter as tk
from PIL import Image, ImageTk

class TransparentCanvas(tk.Canvas):
    def __init__(self, master, **kwargs):
        super().__init__(master, **kwargs)
        self.images = []
    
    def create_transparent_rectangle(self, x1, y1, x2, y2, **options):
        """Create rectangle with alpha transparency support"""
        if 'alpha' in options:
            alpha = options.pop('alpha')
            fill_color = options.pop('fill', 'black')
            
            # Calculate dimensions
            width = abs(x2 - x1)
            height = abs(y2 - y1)
            
            # Convert color and create transparent image
            rgb_color = self.winfo_rgb(fill_color)
            rgba_color = tuple(int(c/256) for c in rgb_color) + (int(alpha * 255),)
            
            image = Image.new('RGBA', (width, height), rgba_color)
            photo = ImageTk.PhotoImage(image)
            self.images.append(photo)
            
            # Create image on canvas
            return self.create_image(min(x1, x2), min(y1, y2), 
                                   image=photo, anchor='nw')
        else:
            # Fall back to regular rectangle
            return self.create_rectangle(x1, y1, x2, y2, **options)

# Create application
root = tk.Tk()
root.title("Custom Transparent Canvas")
root.geometry("600x400")

# Create custom canvas
canvas = TransparentCanvas(root, bg='lightgray')
canvas.pack(fill='both', expand=True)

# Create various transparent shapes
canvas.create_transparent_rectangle(50, 50, 200, 150, fill='purple', alpha=0.4)
canvas.create_transparent_rectangle(120, 100, 300, 200, fill='orange', alpha=0.6)
canvas.create_transparent_rectangle(180, 80, 350, 180, fill='cyan', alpha=0.3)

# Add a regular rectangle for comparison
canvas.create_rectangle(400, 50, 550, 150, fill='yellow', outline='black')

root.mainloop()
The window shows multiple overlapping transparent rectangles alongside a regular opaque rectangle for comparison.

Key Parameters

Parameter Description Range
alpha Transparency level 0.0 (transparent) to 1.0 (opaque)
fill Rectangle color Color name or hex code
x1, y1, x2, y2 Rectangle coordinates Pixel positions

Important Notes

  • PIL Requirement: Install Pillow using pip install Pillow
  • Image Storage: Keep references to PhotoImage objects to prevent garbage collection
  • Performance: Creating many transparent shapes may impact performance
  • RGBA Format: Uses RGBA (Red, Green, Blue, Alpha) for transparency support

Conclusion

Creating transparent rectangles in Tkinter requires PIL to generate RGBA images with alpha channels. Store image references to prevent garbage collection, and use alpha values between 0.0 (fully transparent) and 1.0 (fully opaque) for desired transparency effects.

Updated on: 2026-03-25T22:23:57+05:30

11K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements