python - 在按下特定键盘时等待 Matplotlib 图中的用户输入

标签 python matplotlib figure

我想要用户输入,然后通过按特定键盘来停止循环。

from __future__ import print_function
import sys
import numpy as np
import matplotlib.pyplot as plt


def press(event):
    print('press', event.key)
    sys.stdout.flush()
    if event.key == 'x':
       visible = xl.get_visible()
       xl.set_visible(not visible)
       fig.canvas.draw()
    if event.key == 'enter':
       cnt.append(1)

cnt=[]
List=[]
fig, ax = plt.subplots()

fig.canvas.mpl_connect('key_press_event', press)

ax.plot(np.random.rand(12), np.random.rand(12), 'go')
xl = ax.set_xlabel('easy come, easy go')
ax.set_title('Press a key')
plt.show()
plt.waitforbuttonpress() #non specific key press!!!

result=cnt[0]+cnt[1]

我想停止循环,等待用户按 Enter 键,然后使用 cnt 继续执行代码。但是,如果我不放置 plt.waitforbuttonpress(),代码就会运行并完成,但如果我放置 plt.waitforbuttonpress(),任何键盘或鼠标按下都会运行并结束整个代码。

最佳答案

代码按我的预期工作(matplotlib 版本 2.0.0 和 TkAgg 后端)您创建一个应该在 plt.show 命令处阻塞的图形。

如果没有,请尝试 matplotlib.use("TkAgg") 更改后端(参见顺序 here )

然后你有几个选择,

1) 在事件处理循环中包含您想要运行的代码,可以在您拥有的事件之后运行,也可以在特殊键下运行。

import numpy as np
import matplotlib.pyplot as plt

def press(event):
    print('press', event.key)
    if event.key == 'enter':
        cnt.append(1)
    if event.key == 'a':
        result = sum(cnt)
        print(result, cnt)

cnt=[]
fig, ax = plt.subplots()
fig.canvas.mpl_connect('key_press_event', press)
ax.plot(np.random.rand(12), np.random.rand(12), 'go')
plt.show()

当您按 a 时,您会假设在按 a 时已按 Enter 8 次。 (8, [1, 1, 1, 1, 1, 1, 1])

2)添加退出命令的退出命令(您可能需要找出优雅退出的最佳方式)

import numpy as np
import matplotlib.pyplot as plt

def press(event):
    print('press', event.key)
    if event.key == 'enter':
        cnt.append(1)
    if event.key == "escape":
        plt.close()

cnt=[]
fig, ax = plt.subplots()
fig.canvas.mpl_connect('key_press_event', press)
ax.plot(np.random.rand(12), np.random.rand(12), 'go')
plt.show()
result = sum(cnt)
print(result, cnt)

然后应该运行 plt.show() 之后的命令。

3)为事件循环设置一个超时,您的代码将在该时间之后运行。

import numpy as np
import matplotlib.pyplot as plt

def press(event):
    print('press', event.key)
    if event.key == 'enter':
        cnt.append(1)

cnt=[]
fig, ax = plt.subplots()
fig.canvas.mpl_connect('key_press_event', press)
ax.plot(np.random.rand(12), np.random.rand(12), 'go')
plt.show(block=False)
plt.waitforbuttonpress()
plt.pause(5.)
result = sum(cnt)
print(result, cnt)

看起来 plt.waitforbuttonpress(time=5.) 应该做类似的事情,但我无法让它工作。

关于python - 在按下特定键盘时等待 Matplotlib 图中的用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48978839/

相关文章:

python - 按列值分组并将其设置为 Pandas 中的索引

python - 如何在遗传算法工具箱Deap中生成0到1之间的随机数

python - 执行脚本后使用 matplotlib 打开多个图形

matlab:具有大量数据点的散点图

python - 在 tkinter 中重新映射默认键绑定(bind)

python - 亚马逊云上的 Docker

matplotlib - matplotlib刻度相对于轴的位置

matplotlib - 根据matplotlib中y值更改曲线的颜色

python - 如何在 tkinter 中显示 matplotlib 图表

html - 部分或图形中的图片库标题?