python键盘模块无法立即检测按键

1 投票
2 回答
35 浏览
提问于 2025-04-14 18:34

首先,我的英语不是很好,希望你能理解我。其次,我是编程新手,所以我对很多事情都不太了解。 我想用这段代码给方向分配按键,让乌龟根据我按的键朝我想要的方向移动。我的代码遇到的问题是,键盘模块能识别前两个按键,乌龟会立即做出反应,但第三个按键("a")却需要我按两次才有效。我真的希望有人能帮我解决这个问题!

import turtle
import keyboard

turtle.screensize(500, 500)
if keyboard.read_key() == "w":
turtle.setheading(90), turtle.forward(400)
elif keyboard.read_key() == "s":
turtle.setheading(270), turtle.forward(400)
elif keyboard.read_key() == "a":
turtle.setheading(180), turtle.forward(400)
else:
""

2 个回答

0

@John Gordon的回答很不错,我想补充一点。通常情况下,keyboard.read_key()这个方法不太常用,因为在按下一个键后,清除键盘输入会比较麻烦,而且通常有更高效的方法可以用keyboard库来实现。

我们可以使用keyboard.add_hotkey()来让我们的程序在按下某个键时调用一个函数。下面是一个简单的例子:

#after importing turtle, keyboard, and doing whatever you want to do

def w_pressed():
    #do something when the key w is pressed

def a_pressed():
    #do something when the key a is pressed

def s_pressed():
    #do something when the key s is pressed

def d_pressed():
    #do something when the key d is pressed

keyboard.add_hotkey('w', w_pressed) #bind the key w to the function w_pressed
keyboard.add_hotkey('a', a_pressed) #bind the key a to the function a_pressed
keyboard.add_hotkey('s', s_pressed) #bind the key s to the function s_pressed
keyboard.add_hotkey('d', d_pressed) #bind the key d to the function d_pressed

这段代码的一个大优点是它不需要循环,所以即使在第一次运行之后,这段代码也能一直正常工作。它还让你可以省去ifelif这些判断语句,这样代码的整体结构会更清晰。我想提一下,这段代码有点重复。可能还有更好的函数,所以一定要查看一下文档

1
if keyboard.read_key() == "w":
    ...
elif keyboard.read_key() == "s":
    ...
elif keyboard.read_key() == "a":
   ...

这是你的问题。每次你调用 read_key() 的时候,它都会从键盘读取一个新的按键。

所以这段代码会读取一个按键,然后把它和 "w" 进行比较。如果不相等,它就会再读取一个按键,然后和 "s" 比较。依此类推……

你应该做的是,只读取一次按键,保存这个按键的值,然后用这个值进行所有的比较:

key = keyboard.read_key()
if key == "w":
    ...
elif key == "s":
    ...

撰写回答