Image within canvas insn't moving

38 Views Asked by At

I'm making a program that acts like a conveyor belt picking up images from a folder and making them go from the rightmost end of the screen to the leftmost end of the screen. The code is the following:

#Import
import os
import random 
from PIL import Image, ImageTk
from tkinter import Tk, Canvas, PhotoImage, NW

# folder path
dir_path = r'C:\Users\Usuario\Downloads\Experiment'

#------------------------------------------------------------Select Random Image--------------------------------------------------------

imgExtension = ["webp"] #Image Extensions to be chosen from
allImages = list()

def chooseRandomImage(directory= dir_path):
    for img in os.listdir(directory): #Lists all files
        ext = img.split(".")[len(img.split(".")) - 1]
        if (ext in imgExtension):
            allImages.append(img)
    choice = random.randint(0, len(allImages) - 1)
    chosenImage = allImages[choice] #Image chosen
    return chosenImage


randomImage = chooseRandomImage()
print(randomImage)

#------------------------------------------------------------Canvas---------------------------------------------------------------
root = Tk()
root.attributes('-transparentcolor','#f0f0f0')

canvas = Canvas(root, width = root.winfo_screenwidth(), height=300)
canvas.pack()
#------------------------------------------------------Image movement setup----------------------------------------------------------
def move_imga():
    # move the image
    canvas.move(img, -5, 0)
    # move again after 25 ms (0.025s)
    canvas.after(25, move_imga)
#-------------------------------------------------------------Image------------------------------------------------------------------
im_O = Image.open(r'C:/Users/Usuario/Downloads/Experiment/'+ randomImage)
new_image = im_O.resize((100, 100))
img = ImageTk.PhotoImage(new_image)
#---------------------------------------------Positioning the Image inside the canvas------------------------------------------------
canvas.create_image(root.winfo_screenwidth()-200, 100, anchor=NW, image = img)

#----------------------------------------------------------Starts the GUI------------------------------------------------------------
move_imga()
root.mainloop()

My intention now was to move img from the right to the left of the screen but I can't make it work.

I was trying to move the image throughout a loop made by canvas.after in which it moved 5 pixels to the left every 25 millisenconds but it doesen't work.

0

There are 0 best solutions below