Advertisement
here2share

# tk_9_colors_interpolate.py

Aug 18th, 2024 (edited)
341
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.42 KB | None | 0 0
  1. # tk_9_colors_interpolate.py
  2.  
  3. import tkinter as tk
  4. from PIL import Image, ImageTk
  5.  
  6. WW, HH = 600, 600
  7.  
  8. root = tk.Tk()
  9. canvas = tk.Canvas(root, width=WW, height=HH)
  10. root.geometry("%dx%d+10+10" % (WW, HH))
  11. canvas.pack()
  12. image = Image.new("RGB", (WW, HH))
  13.  
  14. def interpolate_color(color1, color2, factor):
  15.     return tuple(int(color1[i] + (color2[i] - color1[i]) * factor) for i in range(3))
  16.  
  17. grid_colors = {
  18.     (0, 0): (255, 255, 255),  # White
  19.     (0, 1): (255, 255, 0),    # Yellow
  20.     (0, 2): (0, 255, 0),      # Green
  21.     (1, 0): (255, 165, 0),    # Orange
  22.     (1, 1): (128, 128, 128),  # Gray (midpoint)
  23.     (1, 2): (0, 0, 255),      # Blue
  24.     (2, 0): (255, 0, 0),      # Red
  25.     (2, 1): (128, 0, 128),    # Purple
  26.     (2, 2): (0, 0, 0)         # Black
  27. }
  28.  
  29. # Interpolate colors for each pixel
  30. for i in range(WW):
  31.     for j in range(HH):
  32.         x = i / (WW - 1) * 2
  33.         y = j / (HH - 1) * 2
  34.         x0, y0 = int(x), int(y)
  35.         x1, y1 = min(x0 + 1, 2), min(y0 + 1, 2)
  36.         fx, fy = x - x0, y - y0
  37.  
  38.         color_top = interpolate_color(grid_colors[(x0, y0)], grid_colors[(x1, y0)], fx)
  39.         color_bottom = interpolate_color(grid_colors[(x0, y1)], grid_colors[(x1, y1)], fx)
  40.         color = interpolate_color(color_top, color_bottom, fy)
  41.  
  42.         image.putpixel((i, j), color)
  43.  
  44. gradient_photo = ImageTk.PhotoImage(image)
  45.  
  46. canvas.create_image(0, 0, anchor=tk.NW, image=gradient_photo)
  47. canvas.update()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement