Python Forum
[Tkinter] Image only moving upwards - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: GUI (https://python-forum.io/forum-10.html)
+--- Thread: [Tkinter] Image only moving upwards (/thread-23316.html)



Image only moving upwards - GalaxyCoyote - Dec-21-2019

I am trying to create pong in canvas (so I can get used to it for potential applications), but I ran into 2 problems.
1. w and s keys move Player 1 upwards only, if I change 1 of the axis then it will go downwards
2. up and down was moving Player 2 instead of Player 1

from tkinter import *
from threading import Timer

## -- Setup -- ##
# Window
window = Tk()
window.title("Pong!")

# Vars

up1 = False
down1 = False
up2 = False
down2 = False

# Images
Ball = PhotoImage(file = "ball.png")
Player = PhotoImage(file = "R.png")
Player2 = PhotoImage(file = "R.png")

# Canvas
Game = Canvas(window, width = 700, height = 500) # Game window
Game.config(bg = "black")
Game.config(scrollregion = Game.bbox(ALL))
Game.pack()

P1 = Game.create_image(20, 250, image = Player) # Player One
Ba = Game.create_image(350, 250, image = Ball) # Ball
P2 = Game.create_image(680, 250, image = Player2) # Player Two

BaX = 0 # Random int for the speed of the ball
BaY = 0 # Random int for the Y axis of the ball

P1Score = 0 # Player 1 Score
P2Score = 0 # Player 2 Score

## -- Def -- ##
def KeyDown(event): # Controller for Key presses
    global up1
    global down1
    global up2
    global down2
    if event.char == "w" or "W":
        up1 = True
    elif event.char == "s" or "S":
        down1 = True
    if event.char == "Up":
        up2 = True
    elif event.char == "Down":
        down2 = True
        
def KeyUp(event): # Controller for Key releases
    global up1
    global down1
    global up2
    global down2
    if event.char == "w" or "W":
        up1 = False
    elif event.char == "s" or "S":
        down1 = False
    if event.char == "Up":
        up2 = False
    elif event.char == "Down":
        down2 = False

def MoveCheck(): # Controller for movment detection
    global up1
    global down1
    global up2
    global down2
    global P1
    global P2
    global Ba
    if up1 == True:
        Game.move(P1, 0, 1)
    elif down1 == True:
        Game.move(P1, 0, -1)
        
    if up2 == True:
        Game.move(P2, 0, -1)
    elif down2 == True:
        Game.move(P2, 0, 1)
    
    window.after(4, MoveCheck)

## -- Main -- ##

window.bind("<Key>", KeyDown)
window.bind("<KeyRelease>", KeyUp)

MoveCheck()
window.mainloop()
I have left the issues for 2 days but I cannot see what the problem with the code is.

NOTE: Sorry for the messy code, still learning canvas.


RE: Image only moving upwards - Larz60+ - Dec-22-2019

FYI without digging into your code, here's a completed version you can examine for comparison: https://github.com/kidscancode/intro-python-code/blob/master/pong%20game.py