我试图能够使用w,a,s和d键在matplotlib图周围移动点,而不必在每次键入字母后都按回车键。这可以使用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_key = readchar.readchar().lower().decode("utf-8")
我想最好在plt.xlim()
循环之前执行plt.ylim()
和while
限制。
如果我不使用plt
,我的plt.pause()
将冻结。我添加了多个plt.pause(0.0001)
以使代码正常工作。参考:Matplotlib ion() function fails to be interactive
另外,在显示图之前,您需要用户输入代码。我将其更改为用户输入之前显示的图。
最好在输入之前将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()
关于python - matplotlib和readchar可以同时工作吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57720280/