在重新创建循环中关闭窗口后的 Matplotlib 图 key_event 连接

问题描述

我有以下极简代码,可以正常工作:一个连续的 while 循环不断绘制我的数据,如果我按下转义键,绘制就会停止。现在,如果关闭 matplotlib 窗口,由于 plt.pause 命令会出现一个新窗口,但现在不再附加 key_event。有没有办法保持新出现的窗口和 key_event 的连接?

代码

import matplotlib.pyplot as plt
import numpy as np

keep_ploting = True


def action():
    def key_event(event):
        if event.key == 'escape':
            global keep_ploting
            keep_ploting = False

    fig = plt.figure()
    while keep_ploting:
        plt.clf()
        x = np.linspace(1,10,100)
        y = np.random.weibull(2,100)

        plt.plot(x,y)
        plt.pause(1e-1)
        fig.canvas.mpl_connect('key_press_event',key_event)

action()

解决方法

当您关闭窗口时,它会创建新的 figure,您应该使用 gcf()(获取当前数字)将 event 分配给新的 figure

while keep_ploting:
    plt.clf()
    x = np.linspace(1,10,100)
    y = np.random.weibull(2,100)

    plt.plot(x,y)
    plt.pause(1e-1)
    
    fig = plt.gcf()  # get current figure
    fig.canvas.mpl_connect('key_press_event',key_event)