matplotlib和readchar能同时工作吗?

2024-09-27 07:31:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用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

Tags: 文件keyimport绘图键入plotmatplotlib字母
1条回答
网友
1楼 · 发布于 2024-09-27 07:31:04

代码中的第一个问题是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更改为qy更改为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()

相关问题 更多 >

    热门问题