我有一个简单的循环绘制从文件夹中读取的数据。它永远循环以更新图表,我想在按ESC时结束程序。到目前为止,我写道
fig = plt.figure()
plt.axes()
while True:
... # loop over data and plot
plt.draw()
plt.waitforbuttonpress(0)
plt.cla()
如果我通过单击X图标关闭图形,程序将以错误结束。我可以通过这样做来避免错误
try:
plt.waitforbuttonpress(0)
except:
break
但我仍然希望能够通过在剧情上按ESC来终止程序。此外,如果我用CTRL + W关闭绘图,则会重新出现该绘图。我尝试添加事件检测,比如
def parse_esc(event):
if event.key == 'press escape':
sys.exit(0)
fig.canvas.mpl_connect('key_press_event', parse_esc)
但它没有检测到ESC。我尝试用close_event
而不是key_press_event
,但sys.exit(0)
给出以下错误
while executing
"140506996271368filter_destroy 836 ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? 0 ?? ?? .140506996230464 17 ?? ?? ??"
invoked from within
"if {"[140506996271368filter_destroy 836 ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? 0 ?? ?? .140506996230464 17 ?? ?? ??]" == "break"} break"
(command bound to event)
我还想删除循环并仅在检测到R时刷新绘图,但这并不重要。
任何帮助表示赞赏,谢谢。
如果有人需要做类似的事情,这就是我所做的
folder = ...
def update():
plt.cla()
for f in os.listdir(folder):
if f.endswith(".dat"):
data = ...
plt.plot(data)
plt.draw()
print('refreshed')
def handle(event):
if event.key == 'r':
update()
if event.key == 'escape':
sys.exit(0)
fig = plt.figure()
plt.axes()
picsize = fig.get_size_inches() / 1.3
fig.set_size_inches(picsize)
fig.canvas.mpl_connect('key_press_event', handle)
update()
input('')