Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
615 views
in Technique[技术] by (71.8m points)

python - tkinter move object on canvas

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()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...