5

I'm new in python. I'm trying to achieve a simple object movement on canvas.

The idea is to simply update X, Y coordinates and redraw the oval.

I've tried to use canvas.update() every time I update coordinates but it doesn't work this way.

class character():
    x = 10
    y = 10
    color = "red"
    canvas.create_oval(x, y, x + 40, y + 40, fill=color)


def moveup():
    character.y -= 10
def moveright():
    character.x += 10
def movedown():
    character.y += 10
def moveleft():
    character.x -= 10


def choose():
    choosen_move = randint(0, 4)

    if choosen_move == 0:
        moveup()
    elif choosen_move == 1:
        moveright()
    elif choosen_move == 2:
        movedown()
    elif choosen_move == 3:
        moveleft()

    print "%s | %s" % (character.x, character.y)
    canvas.update()
    sleep(1)


while True:
    choose()
root.mainloop()

2 Answers 2

4

Instead of character.x += 10 or character.y -= 10, you need to use move:

canvas.move(oval, 10, 0)   #  for x += 10
canvas.move(oval, 0, -10)  #  for y -= 10

The rest should follow.

Instead of a Character class, you can just say oval = canvas.create_oval(x, y, x + 40, y + 40, fill=color).

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your answer. I tried to use this approach. I made a simple function that runs every time you click the button. It works. Every click moves the oval by 10. But when I try to use a loop to move the oval it shows up at the final position. For example for i in range(5): canvas.move(oval, 10, 0) it moves the oval +50 and then shows up
I solved this problem. root.after(2000, task) Thank you
0

**Please note: none of this code will work - it's just here to give you ideas about how to do stuff. :)

I've had objects bound to the keyboard that move around the screen when buttons are pressed.

instead of a loop, you can just change the x and y of an object with config and bind... when you press left on the keyboard the def will be run which moves the thing. (or things)

def move_object_left()...
   object.config(move left...)

example of binding something:

entry.bind('<ButtonRelease-1>', lambda event: self.maximise_keyboard(event.widget))

x_var = 5 y_var = 9

**Bind an object to the keyboard here:

*On_key_press('RIGHT'):
    x_var = x_var + 5
    object.config(x = x_var)

You can move a bunch of stuff at once if you want... (though you will have to do the code yourself lol)

list_of_stuff = [tree, bush, snail]

    for entry in list_of_stuff:
        ...
        **Get object X and Y of the object...
        ** add a number to this X and Y...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.