无法使用graphics.py和pynput移动图形

时间:2019-09-07 12:42:29

标签: python-3.x graphics pynput

我正在尝试使用pynput在python中移动单个点,但是它不会移动

我已经尝试过使import numpy as np a = [[ 'Apples', '100' ], [ 'Oranges', '50' ], [ 'Pears', '200' ] ] A = np.array(a) # select a column col = A[:, 0] # select a row row = A[0, :] 的点数和点数增加10

keyboard.press("W")

没有错误消息

1 个答案:

答案 0 :(得分:0)

第一件事:pynputkeyboard库做同样的事情,因此您只需要使用其中之一即可。由于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)