第一件事:pynput 和 keyboard 库做同样的事情,所以你只需要使用其中一个。由于keyboard 在Linux 上似乎需要root 权限,我建议使用pynput。
不要重复使用相同的名称。 keyboard 已经是一个包了,不要用它作为变量名。
keyboard.Controller() 用于控制键盘,而不是用于读取它。您可能正在寻找的是keyboard.Listener。
使用keyboard.Listener,您无法直接检查按键,而是在按键被按下或释放时收到通知。这些通知(=回调)函数必须在其构造函数中提供给keyboard.Listener。
然后,您可以在按键被按下时直接应用操作,或者您可以在全局变量中跟踪当前按键状态,如下所示:
# The global dict that keeps track of the keyboard state
key_state = {}
# The function that gets called when a key gets pressed
def key_down(val):
global key_state
key_state[val] = True
# The function that gets called when a key gets released
def key_up(val):
global key_state
key_state[val] = False
# Initializes the keyboard listener and sets the functions 'key_down' and 'key_up'
# as callback functions
keyboard_listener = keyboard.Listener(on_press=key_down, on_release=key_up)
keyboard_listener.start()
然后我们可以在我们的程序中检查一个键是否被按下:
if key_state.get(keyboard.KeyCode(char='w')):
整个程序如下所示:
from graphics import *
from pynput import *
import time
pointx = 250
pointy = 250
win = GraphWin("test", 500, 500)
pt = Point(pointx, pointy)
pt.draw(win)
# The global dict that keeps track of the state of 'w'
key_state = {}
# The function that gets called when a key gets pressed
def key_down(val):
global key_state
key_state[val] = True
# The function that gets called when a key gets released
def key_up(val):
global key_state
key_state[val] = False
# Initializes the keyboard listener and sets the functions 'key_down' and 'key_up'
# as callback functions
keyboard_listener = keyboard.Listener(on_press=key_down, on_release=key_up)
keyboard_listener.start()
# Continuously loop and update the window (important so it doesn't freeze)
while win.isOpen():
win.update()
time.sleep(0.01)
# Little bit of trickery:
# We combine the check if the key exists and if its value is 'true' in one
# single operation, as both 'None' and 'False' are the same value for 'if'.
if key_state.get(keyboard.KeyCode(char='w')):
pt.move(10, 10)