Python matplotlib和readchar可以同时工作吗?

Python matplotlib和readchar可以同时工作吗?,python,matplotlib,Python,Matplotlib,我正在尝试使用w、a、s和d键在matplotlib绘图周围移动一个点,而不必在每次键入字母后都按enter键。这可以使用readchar.readchar()实现,但随后不会显示绘图。我做错了什么 """ Moving dot """ import matplotlib.pyplot as plt import time import readchar x = 0 y = 0 q = 0 e = 0 counter = 0 while 1 : #arrow_key = input()

我正在尝试使用w、a、s和d键在matplotlib绘图周围移动一个点,而不必在每次键入字母后都按enter键。这可以使用readchar.readchar()实现,但随后不会显示绘图。我做错了什么

""" Moving dot """
import matplotlib.pyplot as plt
import time
import readchar

x = 0
y = 0
q = 0
e = 0
counter = 0
while 1 :
    #arrow_key = input()
    arrow_key = readchar.readchar()
    print(x,y)
    if arrow_key == "d" :
        q = x + 1
    elif arrow_key == "a" :
        q = x - 1
    elif arrow_key == "w" :
        e = y + 1
    elif arrow_key == "s" :
        e = y - 1
    plt.ion()   
    plt.plot(x,y, "wo", markersize = 10)
    plt.plot(q,e, "bo")
    plt.xlim(-10,10)
    plt.ylim(-10,10)
    x = q
    y = e

代码中的第一个问题是readchar.readchar()返回二进制字符串。您需要将其解码为utf-8:
arrow\u key=readchar.readchar().lower().decode(“utf-8”)

我认为最好在
while
循环之前执行
plt.xlim()
plt.ylim()
限制

如果我没有使用
plt.pause()
,我的
plt
将冻结。我添加了多个
plt.pause(0.0001)
以使代码正常工作。参考:

此外,在显示绘图之前,需要用户在代码中输入。我将其更改为用户输入前显示的绘图

最好在输入之前将
x
更改为
q
并将
y
更改为
e
。正是在输入之后,我才看到前面的图

编辑:正如FriendFX在下面建议的那样,最好将绘图定义为变量(
pl1=plt.plot(x,y,“wo”,markersize=10)
pl2=plt.plot(q,e,“bo”)
),并在使用后将其删除,以不填充内存
pl1.pop(0).remove()
pl2.pop(0).remove()

完整修复代码如下。请注意,在启动过程中,可能会丢失终端窗口焦点,这对输入至关重要

import matplotlib.pyplot as plt
import time # you didn't use this, do you need it?
import readchar

x = 0
y = 0
q = 0
e = 0
plt.xlim(-10,10)
plt.ylim(-10,10)

counter = 0 # you didn't use this, do you need it?
while(1):
    plt.ion()
    plt.pause(0.0001)
    pl1 = plt.plot(x,y, "wo", markersize = 10)
    pl2 = plt.plot(q,e, "bo")
    plt.pause(0.0001)
    plt.draw()
    plt.pause(0.0001)
    x = q
    y = e

    arrow_key = readchar.readchar().lower().decode("utf-8")
    print(arrow_key)

    if arrow_key == "d" :
        q = x + 1
    elif arrow_key == "a" :
        q = x - 1
    elif arrow_key == "w" :
        e = y + 1
    elif arrow_key == 's' :
        e = y - 1
    print(q, e, x, y)
    pl1.pop(0).remove()
    pl2.pop(0).remove()

不错。根据OP的需要,删除带有
lines.pop(0).remove()
的现有绘图点也可能会有所帮助,如中所述,其中
lines
是一个变量,用于存储
plt.plot()
调用的一个(或两个)输出,例如
line=plot.plot(q,e,“bo”)
。另外,我认为循环中不需要调用
show()
。@FriendFX您是对的。添加您的建议并删除
plt.show()