Ernxst Ernxst - 1 month ago 9
Python Question

Why does my object move in the wrong direction

I have a made a simple program which is meant to move a ball left and right horizontally within a canvas. The user will use the left and right keys to move the ball accordingly by 5 pixels a time. If the x coordinate of the ball is less than 40 or more than 240 then it will do nothing.

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

window = tk.Tk()
game_area = tk.Canvas(width=270, height=400, bd=0, highlightthickness=0,
bg="white")

ball = game_area.create_oval(10, 10, 24, 24, fill="red")
game_area.move(ball, 120, 4)
coords = 120

def move_left(event):
global coords
if coords < 40:
pass
else:
coords = int(coords)- 5
game_area.move(ball, coords, 4)
game_area.update()

def move_right(event):
global coords
if coords > 240:
pass
else:
coords = int(coords)+5
game_area.move(ball, coords, 4)
game_area.update()

window.bind("<Left>", move_left)
window.bind("<Right>", move_right)
game_area.pack()
window.mainloop()


However, pressing either key moves the ball towards the right (more than 5 pixels across) and off the screen despite the
if
function which is meant to prevent this.

Answer

According to the Tkinter Canvas documentation, the second argument to the move method, dx, is an offset. Try calling it like

game_area.move(ball, -5, 4)

Then you don't need the following line, either.

coords = int(coords)- 5
Comments