Python 中如何检查是否同时释放了 2 个键?

How do I check if 2 keys are released at the same time in Python?

在 python 中,我正在尝试制作一款与 Pong 类似的球拍游戏。我有这段代码可以在 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 是桨的速度,也指示方向。但是,此代码导致用户只需按一下键,然后桨就会改变方向。我想让它做的是让用户必须按住键才能移动。我无法告诉它停止移动。我有一个想法,但是行不通

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

有谁知道如何检查左右键是否同时松开?谢谢!

也许您想多了:您可以在按下 Left 键时向左移动桨,在按下 Right 键时向右移动桨,而忽略 KeyRelease 事件。

以下示例对桨的行为进行编码,使得桨在按下 Left 键时向左移动,在松开时停止,在按下 Right 键时向右移动。

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()