Ernxst Ernxst - 1 year ago 110
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.

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,

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:
coords = int(coords)- 5
game_area.move(ball, coords, 4)

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

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

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

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download