Advertisement
here2share

# tk_masked_demo.py

Jan 23rd, 2024
954
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.92 KB | None | 0 0
  1. # tk_masked_demo.py
  2.  
  3. import tkinter as tk
  4. from PIL import Image, ImageDraw, ImageTk, ImageFilter, ImageOps
  5. import random
  6.  
  7. # Create a 500x500 canvas
  8. canvas_width = 500
  9. canvas_height = 500
  10.  
  11. root = tk.Tk()
  12. canvas = tk.Canvas(root, width=canvas_width, height=canvas_height)
  13. canvas.pack()
  14.  
  15. # Generate the colorful checkerboard image
  16. checkerboard = Image.new('RGB', (canvas_width, canvas_height), (255, 255, 255))
  17. draw = ImageDraw.Draw(checkerboard)
  18. square_size = 50
  19. colors = []
  20. t = [z for z in range(0, 256, 35)]
  21. for r in t:
  22.     for g in t:
  23.         for b in t:
  24.             colors += [(r, g, b, 255)]
  25. random.shuffle(colors)
  26.  
  27. for i in range(0, canvas_width, square_size):
  28.     for j in range(0, canvas_height, square_size):
  29.         color = colors.pop()
  30.         draw.rectangle([i, j, i + square_size, j + square_size], fill=color)
  31. checkerboard = checkerboard.filter(ImageFilter.GaussianBlur(radius=20))
  32.  
  33. polka_dot = Image.new('RGBA', (canvas_width, canvas_height), (255, 255, 255, 0))
  34. draw = ImageDraw.Draw(polka_dot)
  35. dot_size = 20
  36. for i in range(0, canvas_width, dot_size+10):
  37.     for j in range(0, canvas_height, dot_size+10):
  38.         color = colors.pop()
  39.         draw.ellipse([i, j, i + dot_size, j + dot_size], fill=color)
  40.        
  41. # Generate the mask
  42. ww = 400
  43. hh = 400
  44. p = 10
  45. mask = Image.new('L', (ww+p, hh+p), 0)
  46. draw = ImageDraw.Draw(mask)
  47. for i in range(0, min(ww+p, hh+p) // 2):
  48.     draw.rectangle([i, i, ww+p - i, hh+p - i], fill=i * 255 // (min(ww+p, hh+p) // 5))
  49. mask_size = (ww+p, hh+p)
  50.  
  51. polka_dot = polka_dot.resize(mask_size)
  52. masked_polka_dot = Image.composite(polka_dot, Image.new('RGBA', mask_size, (255, 255, 255, 0)), mask)
  53.  
  54. checkerboard_tk = ImageTk.PhotoImage(checkerboard)
  55. canvas.create_image(0, 0, anchor=tk.NW, image=checkerboard_tk)
  56.  
  57. masked_polka_dot_tk = ImageTk.PhotoImage(masked_polka_dot)
  58. canvas.create_image((canvas_width // 2, canvas_height // 2), anchor=tk.CENTER, image=masked_polka_dot_tk)
  59.  
  60. root.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement