Advertisement
here2share

# Tk_Voronoi.py

Nov 14th, 2020 (edited)
1,190
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.37 KB | None | 0 0
  1. # tk_Voronoi.py
  2.  
  3. from tkinter import *
  4. from PIL import Image, ImageTk
  5. import random
  6. import math
  7. import time
  8.  
  9. # Define constants
  10. ww = 300
  11. hh = 300
  12. rgb = [i for i in range(0, 256, 50)]
  13. colors = [(r, g, b) for r in rgb for g in rgb for b in rgb][100:-40]
  14. L = len(colors)
  15.  
  16. xy2field = {}
  17. c = 0
  18. for y in range(hh):
  19.     for x in range(ww):
  20.         xy2field[x,y] = c
  21.         c += 1
  22.        
  23. XY = [0] * (ww * hh)
  24.  
  25. # Define function for calculating distance between two points
  26. def distance(x1, y1, x2, y2):
  27.     return (x1 - x2)**2 + (y1 - y2)**2 # no need to get exact distance
  28.  
  29. rndi = random.randint
  30. def Voronoi(numPoints):
  31.     basePoints = []
  32.     for i in range(numPoints):
  33.         x = rndi(0, ww)
  34.         y = rndi(0, hh)
  35.         basePoints.append((x, y, colors[i%L]))
  36.    
  37.     for y in range(hh):
  38.         for x in range(ww):
  39.             distances = []
  40.             for px, py, color in basePoints:
  41.                 distances.append([distance(x, y, px, py), color])
  42.             sorted_distances = sorted(distances)
  43.             points[xy2field[x,y]] = sorted_distances[0][-1]
  44.          
  45.     return points
  46.  
  47. root = Tk()
  48. root.title("Tk Voronoi")
  49. root.geometry("%dx%d+-10+0"%(ww,hh))
  50. canvas = Canvas(root, width=ww, height=hh)
  51. canvas.pack()
  52.  
  53. while 1:
  54.     random.shuffle(colors)
  55.     points = XY[:]
  56.     pixels = Voronoi(30)
  57.     img = Image.new("RGB", (ww,hh))
  58.     img.putdata(pixels)
  59.  
  60.     imgTk = ImageTk.PhotoImage(img)
  61.     canvas.create_image(0, 0, anchor=NW, image=imgTk)
  62.     canvas.update()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement