Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # tk_bouncing_sq_RndColors.py
- import tkinter as tk
- import random
- ww = 1000
- hh = 300
- # Create the main window
- window = tk.Tk()
- window.geometry(f"{ww}x{hh}+0+0")
- window.title("Bouncing Square Random Colors")
- # Create the canvas
- canvas = tk.Canvas(window, width=ww, height=hh)
- canvas.pack()
- # Set up variables
- dy = 20
- dx = 20
- x1 = 0
- y1 = 0
- # Function to handle the animation
- def animate():
- global x1, y1, dx, dy
- x1 = x1 + dx
- y1 = y1 + dy
- x2 = x1 + 100
- y2 = y1 + 100
- if x1 < 0:
- dx = -1 * dx
- if y1 < 0:
- dy = -1 * dy
- if x1 > ww-100:
- dx = -1 * dx
- if y1 > hh-100:
- dy = -1 * dy
- color = "#{:06x}".format(random.randint(0, 0xffffff))
- canvas.delete("square")
- canvas.create_rectangle(x1, y1, x2, y2, fill=color, tags="square")
- window.after(100, animate)
- # Call the animate function to start the animation
- animate()
- # Run the main loop
- window.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement