Advertisement
here2share

# tk_circle_packing.py

Dec 19th, 2022
653
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.27 KB | None | 0 0
  1. # tk_circle_packing.py
  2.  
  3. import tkinter as tk
  4. import random
  5.  
  6. ww = 500
  7. hh = 500
  8.  
  9. # Create the root window
  10. root = tk.Tk()
  11. root.title("tk_circle_packing.py")
  12.  
  13. # Create a canvas to draw on
  14. canvas = tk.Canvas(root, width=ww, height=hh)
  15. canvas.pack()
  16.  
  17. # Generate a list of random colors
  18. colors = ["red", "orange", "yellow", "green", "blue", "purple"]
  19. L = len(colors)
  20.  
  21. # Generate a list of random diameter sizes from 200 to 10
  22. sizes = [i for i in (101,80,70,50,21,10,5)]
  23.  
  24. # Create a list to store the coordinates of the center of each circle
  25. centers = []
  26.  
  27. XY_main = [(x, y) for x in range(ww) for y in range(hh)]
  28.  
  29. # Generate the circles
  30. for size in sizes:
  31.     xy = XY_main[:]
  32.     random.shuffle(xy)
  33.     for x,y in xy:
  34.         # Check if the circle overlaps with any of the other circles
  35.         overlap = False
  36.         for center in centers:
  37.             distance = ((center[0] - x) ** 2 + (center[1] - y) ** 2) ** 0.5
  38.             if distance < size + center[2]:
  39.                 overlap = True
  40.                 break
  41.  
  42.         # If the circle does not overlap, draw it and add its center to the list of centers
  43.         if not overlap:
  44.             color = colors[len(centers)%L]
  45.             canvas.create_oval(x - size, y - size, x + size, y + size, fill=color)
  46.             centers.append((x, y, size))
  47.             canvas.update()
  48.  
  49. # Run the Tkinter event loop
  50. root.mainloop()
  51.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement