1
votes

In python, I'm trying to get a game with paddles working similar to Pong. I have this code for moving a paddle within a tkinter canvas.

self.canvas.bind_all("<KeyPress-Left>", self.change_dir)
self.canvas.bind_all("<KeyPress-Right>", self.change_dir)
...
def change_dir(self, e):
   if e.keysym == "Left":
       self.x = -2
   elif e.keysym == "Right":
       self.x = 2

self.x is the speed for the paddle that also indicates direction. However, this code results in the user only having to press the key once and then the paddle will change direction. What I want it to do is for the user to have to hold down the key for it to move. There is no way for me to tell it to stop moving. I have an idea, but it doesn't work.

self.canvas.bind_all("<KeyRelease-Right><KeyRelease-Left>", self.change_dir)

Does anyone know how I can check if the Right and Left keys are released at the same time? Thanks!

1
Why do you need them at the same time? Can’t you just add them separately? - Sami Kuhmonen
Even if physically released at the same time the keycodes will be send one after the other. - Klaus D.
You can bind <KeyRelease-Left> and <KeyRelease-Right> to a callback and set self.x = 0 in the callback. - acw1668

1 Answers

1
votes

Maybe you are overthinking this: You could move the paddle left upon pressing the Left key, and right upon pressing the Right key, and ignore KeyRelease events.

The following example codes the behavior of the paddle such that the paddle moves left upon pressing the Left key, stops when it is released, and moves right upon pressing the Right key.

import tkinter as tk


def move_paddle(event=None):
    dx = 0
    if event.keysym == "Left":
        dx = -1
    elif event.keysym == 'Right':
        dx = 1
    x0, y0, x1, y1 = canvas.coords(paddle)
    if x0 < 1:
        dx, x0, x1 = 0, 1, PADDLEWIDTH + 1
    elif x1 > WIDTH:
        dx, x0, x1 = 0, WIDTH - PADDLEWIDTH, WIDTH
    canvas.coords(paddle, x0+dx, y0, x1+dx, y1)        


WIDTH, HEIGHT = 100, 30
PADDLEWIDTH = 30

root = tk.Tk()
canvas = tk.Canvas(root, width=WIDTH, height = HEIGHT)
canvas.pack(expand=True, fill=tk.BOTH)

paddle = canvas.create_rectangle((10, 10), (40, 20), fill='red', outline='black')
canvas.bind_all("<KeyPress-Right>", move_paddle)
canvas.bind_all("<KeyPress-Left>", move_paddle)

root.mainloop()