need help to get my python image to move around using tkinter

Peter Otten __peter__ at web.de
Fri Nov 18 14:06:13 EST 2016


twgrops--- via Python-list wrote:

> Hi I am new here and to python,
> 
> I am currently studying towards my degree in computer science and have to
> build a program but I have hit a brick wall. I am trying to make an image
> move around the canvas. I can make a rectangle move using the following:
> 
> #test rectangle
> id1=canvas.create_rectangle(3,7,3+10,7+10)
> 
> # Generate x and y coordinates for 500 timesteps
> for t in range(1, 500):
> 
>     x1,y1,x2,y2=canvas.coords(id1)
> 
>     # If a boundary has been crossed, reverse the direction
>     if x1 >= x_max:
>          vx = -10.0
>     if y1 <= y_min:
>          vy = 5.0
>     if y2 >= y_max:
>          vy = -5.0
>     if x1 <= x_min:
>          vx = 10.0
> 
>     # Reposition the robot
>     canvas.coords(id1,x1+vx,y1+vy,x2+vx,y2+vy)
>     canvas.update()
> 
>     # Pause for 0.1 seconds, then delete the image
>     time.sleep(0.1)

You should never use sleep() in conjunction with tkinter. Instead make a 
little function that schedules itself for invocation after a few 
milliseconds:

def move():
   ... # move sprits
   root.after(100, move) # have tkinter call move() 
                         # again after 100 milliseconds

That way the event loop is undisturbed and the application can respond to 
user input.

> However i would like my image/sprite to move around:
> 
> objecttank=canvas.create_image(950,650,image=gif6, anchor= NW)
> 
> from what i gather it is because an image only has two axis, x and y but
> the rectangle seems to have 4 values, my error code keeps saying expecting
> 4 but got 2.

Always provide the exact code causing the error, and the traceback it 
generated. Use copy and paste instead of paraphrasing.
 
> Can anyone help me in the right direction, many thanks tom.

I think I have done this before, but cannot find it atm, so instead of a 
link here's a new demo:

try:
    import tkinter as tk
except ImportError:
    import Tkinter as tk

import random

WIDTH = 1024
HEIGHT = 768


def random_speed():
    return random.choice([-1, 1]) * random.randrange(5, 15)


def random_image(canvas, image):
    """Place `image` on `canvas` with random pos and speed.
    """
    return Image(
        canvas,
        image,
        random.randrange(WIDTH-image.width()),
        random.randrange(HEIGHT-image.height()),
        random_speed(),
        random_speed(),
    )


class Image(object):
    def __init__(self, canvas, image, x, y, vx, vy):
        self.canvas = canvas
        self.image = image
        self.x = x
        self.y = y
        self.vx = vx
        self.vy = vy
        self.w = image.width()
        self.h = image.height()
        self.id = canvas.create_image(x, y, image=image, anchor=tk.NW)

    @property
    def right(self):
        return self.x + self.w

    @property
    def bottom(self):
        return self.y + self.h

    def move(self):
        self.x += self.vx
        self.y += self.vy
        self.canvas.move(self.id, self.vx, self.vy)
        if self.bottom > HEIGHT or self.y < 0:
            self.vy = - self.vy
        if self.right > WIDTH or self.x < 0:
            self.vx = - self.vx


def move():
    for image in images:
        image.move()
    root.after(50, move)


if __name__ == "__main__":
    root = tk.Tk()
    ball = tk.PhotoImage(file="ball.gif")
    canvas = tk.Canvas(root, width=WIDTH, height=HEIGHT)
    canvas.pack()
    images = [random_image(canvas, ball) for _ in range(10)]
    move()
    root.mainloop()





More information about the Python-list mailing list