我正在尝试使用w、a、s和d键在matplotlib plot周围移动一个点,而不必每次键入字母后都按回车键。它使用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")
我想说,在
while
循环之前,最好先做plt.xlim()
和plt.ylim()
限制。你知道吗如果我不使用
plt.pause()
,我的plt
就会冻结。我添加了多个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()
完整修复代码如下。请注意,在启动时,可能会丢失终端窗口焦点,这对输入至关重要。你知道吗
相关问题 更多 >
编程相关推荐