Python Forum
[Tkinter] Image only moving upwards
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tkinter] Image only moving upwards
#1
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.
Reply
#2
FYI without digging into your code, here's a completed version you can examine for comparison: https://github.com/kidscancode/intro-pyt...%20game.py
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020