Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # tk_masked_demo.py
- import tkinter as tk
- from PIL import Image, ImageDraw, ImageTk, ImageFilter, ImageOps
- import random
- # Create a 500x500 canvas
- canvas_width = 500
- canvas_height = 500
- root = tk.Tk()
- canvas = tk.Canvas(root, width=canvas_width, height=canvas_height)
- canvas.pack()
- # Generate the colorful checkerboard image
- checkerboard = Image.new('RGB', (canvas_width, canvas_height), (255, 255, 255))
- draw = ImageDraw.Draw(checkerboard)
- square_size = 50
- colors = []
- t = [z for z in range(0, 256, 35)]
- for r in t:
- for g in t:
- for b in t:
- colors += [(r, g, b, 255)]
- random.shuffle(colors)
- for i in range(0, canvas_width, square_size):
- for j in range(0, canvas_height, square_size):
- color = colors.pop()
- draw.rectangle([i, j, i + square_size, j + square_size], fill=color)
- checkerboard = checkerboard.filter(ImageFilter.GaussianBlur(radius=20))
- polka_dot = Image.new('RGBA', (canvas_width, canvas_height), (255, 255, 255, 0))
- draw = ImageDraw.Draw(polka_dot)
- dot_size = 20
- for i in range(0, canvas_width, dot_size+10):
- for j in range(0, canvas_height, dot_size+10):
- color = colors.pop()
- draw.ellipse([i, j, i + dot_size, j + dot_size], fill=color)
- # Generate the mask
- ww = 400
- hh = 400
- p = 10
- mask = Image.new('L', (ww+p, hh+p), 0)
- draw = ImageDraw.Draw(mask)
- for i in range(0, min(ww+p, hh+p) // 2):
- draw.rectangle([i, i, ww+p - i, hh+p - i], fill=i * 255 // (min(ww+p, hh+p) // 5))
- mask_size = (ww+p, hh+p)
- polka_dot = polka_dot.resize(mask_size)
- masked_polka_dot = Image.composite(polka_dot, Image.new('RGBA', mask_size, (255, 255, 255, 0)), mask)
- checkerboard_tk = ImageTk.PhotoImage(checkerboard)
- canvas.create_image(0, 0, anchor=tk.NW, image=checkerboard_tk)
- masked_polka_dot_tk = ImageTk.PhotoImage(masked_polka_dot)
- canvas.create_image((canvas_width // 2, canvas_height // 2), anchor=tk.CENTER, image=masked_polka_dot_tk)
- root.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement