Advertisement
here2share

# tk_bouncing_sq_RndColors.py

Jan 19th, 2024
1,045
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.96 KB | None | 0 0
  1. # tk_bouncing_sq_RndColors.py
  2.  
  3. import tkinter as tk
  4. import random
  5.  
  6. ww = 1000
  7. hh = 300
  8.  
  9. # Create the main window
  10. window = tk.Tk()
  11. window.geometry(f"{ww}x{hh}+0+0")
  12. window.title("Bouncing Square Random Colors")
  13.  
  14. # Create the canvas
  15. canvas = tk.Canvas(window, width=ww, height=hh)
  16. canvas.pack()
  17.  
  18. # Set up variables
  19. dy = 20
  20. dx = 20
  21. x1 = 0
  22. y1 = 0
  23.  
  24. # Function to handle the animation
  25. def animate():
  26.     global x1, y1, dx, dy
  27.  
  28.     x1 = x1 + dx
  29.     y1 = y1 + dy
  30.     x2 = x1 + 100
  31.     y2 = y1 + 100
  32.  
  33.     if x1 < 0:
  34.         dx = -1 * dx
  35.     if y1 < 0:
  36.         dy = -1 * dy
  37.     if x1 > ww-100:
  38.         dx = -1 * dx
  39.     if y1 > hh-100:
  40.         dy = -1 * dy
  41.  
  42.     color = "#{:06x}".format(random.randint(0, 0xffffff))
  43.  
  44.     canvas.delete("square")
  45.     canvas.create_rectangle(x1, y1, x2, y2, fill=color, tags="square")
  46.  
  47.     window.after(100, animate)
  48.  
  49. # Call the animate function to start the animation
  50. animate()
  51.  
  52. # Run the main loop
  53. window.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement