Кнопки в Matplotlib не работают при открытии окна из другого окна - PullRequest
0 голосов
/ 19 марта 2020

Следующий минимальный рабочий пример открывает окно с одной кнопкой:

enter image description here

При нажатии кнопки появляется следующее окно, которое содержит, среди другие вещи, две кнопки, которые не работают:

enter image description here

При нажатии кнопки True все линии с красными крестиками должны исчезнуть. С другой стороны, при повторном нажатии кнопки All полный список должен появиться снова. В настоящее время это не работает. Что я делаю неправильно? Как улучшить мой код?

Вот код, который производит цифры:

import matplotlib.pyplot as plt
from matplotlib.widgets import Button

class Index(object):
    def __init__(self, ax, chars, is_true):
        self.ax = ax
        self.chars = chars
        self.is_true = is_true

    def select_all(self, _):
        self.ax.cla()
        y = 0
        dy = 0.1
        for i, s in enumerate(self.chars):
            if self.is_true[i]:
                self.ax.text(0.0, y, ha='left', fontsize=25, s='o', c='lime')
            else:
                self.ax.text(0.0, y, ha='left', fontsize=25, s='x', c='red')
            self.ax.text(0.5, y, s=s, ha='left', wrap=True)
            y += dy
        self.ax.axis('off')
        plt.draw()

    def select_true(self, _):
        self.ax.cla()
        y = 0
        dy = 0.1
        for i, s in enumerate(self.chars):
            if self.is_true[i]:
                self.ax.text(0.0, y, ha='left', fontsize=25, s='o', c='lime')
                self.ax.text(0.5, y, s=s, ha='left', wrap=True)
                y += dy
        self.ax.axis('off')
        plt.draw()

def plot2():
    # Data
    chars = ['The', 'quick', 'brown', 'fox', 'jumps']
    is_true = [True, False, True, False, True]

    # Initial plot
    fig, ax = plt.subplots()
    plt.subplots_adjust(bottom=0.2)
    ax.axis('off')

    y = 0
    dy = 0.1
    for i, s in enumerate(chars):
        if is_true[i]:
            ax.text(0.0, 0.1*i, ha='left', fontsize=25, s='o', c='lime')
        else:
            ax.text(0.0, 0.1*i, ha='left', fontsize=25, s='x', c='red')
        ax.text(0.5, 0.1*i, s=s, ha='left', wrap=True)
        y += dy

    callback = Index(ax, chars, is_true)
    width = 0.15
    height = 0.1
    dx = 0.005
    x_pos = 0.0
    y_pos = 0.0

    axall = plt.axes([x_pos, y_pos, width, height])
    button_all= Button(axall, 'All')
    button_all.on_clicked(callback.select_all)
    x_pos += width + dx

    axtrue = plt.axes([x_pos, y_pos, width, height])
    button_true = Button(axtrue, 'True')
    button_true.on_clicked(callback.select_true)
    x_pos += width + dx

    plt.show()

def open_plot(_):
    plot2()

def plot_1():
    fig, ax = plt.subplots()
    button = Button(ax, 'Push to open!')
    button.on_clicked(open_plot)
    plt.show()

if __name__ == '__main__':
    plot_1()
...