NukeInTheShell
NukeInTheShell

Reputation: 3

Bouncing dvd logo in python tkinter

I am trying to make a bouncing DVD logo in tkinter, but I don't really know how to make it, it works with a ball, the logo doesn't move. The logo

# 1) create main window
from tkinter import *
from PIL import ImageTk, Image
fen = Tk()
fen.title('AllTech - Bouncing ball')
fen.resizable(False, False)

# 2) create canvas and ball
WIDTH, HEIGHT = 400, 300
canvas = Canvas(fen, width=WIDTH, height=HEIGHT)
canvas.pack()

img = ImageTk.PhotoImage(Image.open("dvd.gif"))
# ball = canvas.create_oval(10, 10, 50, 50, fill='black')

# 3) move the ball
xspeed = yspeed = 3


frame = Frame(fen, width=600, height=400)
frame.pack()
frame.place(anchor='center', relx=0.5, rely=0.5)

label = Label(frame, image = img)
label.pack()


def moveBall():

    global xspeed, yspeed

    canvas.move(canvas, xspeed, yspeed)

    (leftPos, topPos, rightPos, bottomPos) = canvas.coords(img)

    if leftPos <= 0 or rightPos >= WIDTH:
        xspeed = -xspeed
    if topPos <= 0 or bottomPos >= HEIGHT:
        yspeed = -yspeed

    img.after(30, moveBall)


canvas.after(30, moveBall)
fen.mainloop()

I tried with a ball ad it's work, but I don't know why, it doesn't with the logo.

Upvotes: 0

Views: 1166

Answers (1)

acw1668
acw1668

Reputation: 47085

You need to put the image using canvas.create_image() and then you can move the image using canvas.move().

from tkinter import *
from PIL import ImageTk, Image

fen = Tk()
fen.title('AllTech - Bouncing ball')
fen.resizable(False, False)

WIDTH, HEIGHT = 400, 300
canvas = Canvas(fen, width=WIDTH, height=HEIGHT, bg="white")
canvas.pack()

img = ImageTk.PhotoImage(Image.open("dvd.gif"))
# put the image into canvas
logo = canvas.create_image(0, 0, image=img, anchor="nw")

xspeed = yspeed = 3

def moveLogo():
    global xspeed, yspeed

    # move the image
    canvas.move(logo, xspeed, yspeed)

    # get bounding box of the image
    (leftPos, topPos, rightPos, bottomPos) = canvas.bbox(logo)

    if leftPos <= 0 or rightPos >= WIDTH:
        xspeed = -xspeed
    if topPos <= 0 or bottomPos >= HEIGHT:
        yspeed = -yspeed

    canvas.after(30, moveLogo)

canvas.after(30, moveLogo)
fen.mainloop()

enter image description here

Upvotes: 0

Related Questions