0

I have wrote a code that it working fine to move the image to bottom, but I am confused how to move it again to the old position of image that is on the top ?

import tkinter as tk

def move_object(canvas, object_id, destination, speed=50):
    dest_x, dest_y = destination
    coords = canvas.coords(object_id)
    current_x = coords[0]
    current_y = coords[1]

    new_x, new_y = current_x, current_y
    delta_x = delta_y = 0
    if current_x < dest_x:
        delta_x = 1
    elif current_x > dest_x:
        delta_x = -1

    if current_y < dest_y:
        delta_y = 1
    elif current_y > dest_y:
        delta_y = -1

    if (delta_x, delta_y) != (0, 0):
        canvas.move(object_id, delta_x, delta_y)

    if (new_x, new_y) != (dest_x, dest_y):
        canvas.after(speed, move_object, canvas, object_id, destination, speed)

root = tk.Tk()
canvas = tk.Canvas(root, width=400, height=400)
canvas.pack()

background = tk.PhotoImage(file="Images/scanner-bar.png")
item1 = canvas.create_image(0,0, image=background, anchor=tk.NW)

move_object(canvas, item1, (0, 180), 2)
move_object(canvas, item1, (0, 0), 2)

root.mainloop()

sodmzs1
  • 324
  • 1
  • 12
  • Simply call `move_object(canvas, item1, (0, 0), 2)`. – acw1668 Dec 17 '20 at 08:03
  • No. This will make the image stuck on 0 x-axis. – sodmzs1 Dec 17 '20 at 08:05
  • If the image is moved to `(0, 180)`. Calling `move_object(canvas, item1, (0, 0), 2)` will move the image back to `(0, 0)`. – acw1668 Dec 17 '20 at 08:08
  • Can you please copy my code and check it on your machine ? By adding `move_object(canvas, item1, (0, 0), 2)` you will understand, how it's stucking on 0 x-axis. – sodmzs1 Dec 17 '20 at 08:11
  • Yes I have tested your code and it works fine. May be you call it without waiting the image to be moved completely. – acw1668 Dec 17 '20 at 08:12
  • I have updated my code, can you please check it's the same code you are executing too ? – sodmzs1 Dec 17 '20 at 08:14
  • You should not call the second `move_object(...)` before the first move completed (i.e the image has been moved to (0, 180)). Otherwise there will be two `after()` periodically tasks running at the same time. That's why I said in my previous comment *"If the image is moved to `(0, 180)`"*. – acw1668 Dec 17 '20 at 08:18
  • You can add `elif (new_x, new_y) != (0, 0): move_object(canvas, object_id, (0, 0), speed)` at the end of `move_object()`. – acw1668 Dec 17 '20 at 08:27

0 Answers0