Monday, July 25, 2022

Animation in tkinter



                              Space.png                                            UFO.png 

from tkinter import *

from time import sleep

from random import randint


WIDTH, HEIGHT = 500, 500

velX, velY = randint(-3, 3), randint(-3, 3)


win = Tk()

win.geometry("500x500")


canvas = Canvas(win, width=WIDTH, height=HEIGHT, bg="light blue")

canvas.place(x=0, y=0)


picSpace = PhotoImage(file="Space.png")

imgSpace = canvas.create_image(0, 0, image=picSpace, anchor=NW)


picUFO = PhotoImage(file="UFO.png")

imgUFO = canvas.create_image(10, 10, image=picUFO, anchor=NW)

imgWidth, imgHeight = picUFO.width(), picUFO.height()


running = True

while running:

  velX, velY = randint(-3, 3), randint(-3, 3)

  print(velX, velY)

  coordinates = canvas.coords(imgUFO)

  if(coordinates[0] >= (WIDTH - imgWidth) or coordinates[0] < 0):

    velX = -velX

  if(coordinates[1] >= (HEIGHT - imgHeight) or coordinates[1] < 0):

    velY = -velY

  canvas.move(imgUFO, velX, velY)

  win.update()

  sleep(0.003)

  

win.mainloop()

No comments:

Post a Comment