我想要用户输入,然后通过按特定键盘来停止循环。
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/