如何从 Tkinter 框架中正确删除图形

亚历山大·卡普舒克

我有几个图表想要在按下按钮时显示。为此,我将plt.FigureFigureCanvasTkAgg变量设为全局,并且每次按下按钮时只需擦除轴ax.clear()之后,我使用Figure.canvas.mpl_connect以下方法添加了一个功能:当我按下图形区域时,第二个点用垂直线突出显示。当我打印一些简单的输出(在我的例子中,print('Vertical Line Constructed')select_trade_with_mouse函数中)时,结果是为每个构建和删除的图形创建了事件:当我生成一个图形并按下图形(生成事件)时,然后print('Vertical Line Constructed')只执行一次。如果我生成第二个图形并单击图形,则print('Vertical Line Constructed')被执行两次。看起来旧图没有被破坏,点击图会为内存中的每个图生成一个事件,即使它没有显示。我试过plt.cla(),plt.clf()plt.close(),但它们都没有完全删除图形。

我的问题是,如何正确删除旧图表?所以点击图表只会产生一个事件?

我的代码:

import pandas as pd
import tkinter as tk
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg


def select_trade_with_mouse(event, ax, graph, data):
    global vertical_line_trading
    print('Vertical Line Constructed')
    if vertical_line_trading:
        vertical_line_trading.remove()
        del vertical_line_trading
    vertical_line_trading = ax.axvline(data, color='b')
    graph.draw()

def construct_graph(change_by = 0):  
    global data
    global graph_index
    print('Graph Constructed')
    graph_index = graph_index + change_by
    ax.clear()
    #plt.close('all')
    line = data[graph_index].plot(x='x', y='y', linestyle='-', ax=ax, linewidth=1, color='y')
    click_id = figure.canvas.mpl_connect('button_press_event', lambda event: select_trade_with_mouse(event, ax, graph, data[graph_index].loc[1, 'x']))    
    graph.draw()


if __name__ == '__main__':

    vertical_line_trading = None
    graph_index = 0

    ## Some random data
    data = []
    for i in range(10):
        data.append(pd.DataFrame({'x': [1+i, 2+i, 3+2*i], 'y': [1+2*i, 2+i, 3+i]}))

    root = tk.Tk()
    main_frame = tk.Frame(root, height=600, width=1200)
    graph_frame = tk.Frame(main_frame, height=500, width=1200)

    ## Graph
    figure = plt.Figure(figsize=(10,10), dpi=100)
    ax = figure.add_subplot(111)
    graph = FigureCanvasTkAgg(figure, graph_frame)
    graph.get_tk_widget().pack(side=tk.LEFT)

    ## Buttons to switch between graphs
    prev_graph_button = tk.Button(graph_frame, command = lambda: construct_graph(-1), height=10, width=10, text='Prev\nGraph')
    next_graph_button = tk.Button(graph_frame, command = lambda: construct_graph(1), height=10, width=10, text='Next\nGraph')
    prev_graph_button.pack(side=tk.LEFT)
    next_graph_button.pack(side=tk.LEFT)

    for frame in [main_frame, graph_frame]:
        frame.pack(side=tk.BOTTOM, fill='both')
        frame.pack_propagate(0)

    root.mainloop()
简单的

您不必删除图形。mpl_connect()只需在开始时使用一次,而在清除图形时不能一次又一次地使用。

或者你必须保持click_id在全局变量中并使用mpl_disconnect(click_id)之前click_id = mpl_connect()

click_id = None在开始时创建全局变量,稍后如果不是,则construct_graph()删除前一个这种方式图只分配了一个功能click_idNone

import pandas as pd
import tkinter as tk
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg


def select_trade_with_mouse(event, ax, graph, data):
    global vertical_line_trading
    print('Vertical Line Constructed')
    if vertical_line_trading:
        vertical_line_trading.remove()
        del vertical_line_trading
    vertical_line_trading = ax.axvline(data, color='b')
    graph.draw()

def construct_graph(change_by = 0):  
    global data
    global graph_index
    global click_id 

    print('Graph Constructed')
    graph_index = graph_index + change_by
    ax.clear()
    #plt.close('all')
    line = data[graph_index].plot(x='x', y='y', linestyle='-', ax=ax, linewidth=1, color='y')

    # if function exist then remove it
    if click_id: # if click_id is not None:
        figure.canvas.mpl_disconnect(click_id)

    click_id = figure.canvas.mpl_connect('button_press_event', lambda event: select_trade_with_mouse(event, ax, graph, data[graph_index].loc[1, 'x']))   

    graph.draw()


if __name__ == '__main__':

    click_id = None # create global varaible with default value at start

    vertical_line_trading = None
    graph_index = 0

    ## Some random data
    data = []
    for i in range(10):
        data.append(pd.DataFrame({'x': [1+i, 2+i, 3+2*i], 'y': [1+2*i, 2+i, 3+i]}))

    root = tk.Tk()
    main_frame = tk.Frame(root, height=600, width=1200)
    graph_frame = tk.Frame(main_frame, height=500, width=1200)

    ## Graph
    figure = plt.Figure(figsize=(10,10), dpi=100)
    ax = figure.add_subplot(111)
    graph = FigureCanvasTkAgg(figure, graph_frame)
    graph.get_tk_widget().pack(side=tk.LEFT)

    ## Buttons to switch between graphs
    prev_graph_button = tk.Button(graph_frame, command = lambda: construct_graph(-1), height=10, width=10, text='Prev\nGraph')
    next_graph_button = tk.Button(graph_frame, command = lambda: construct_graph(1), height=10, width=10, text='Next\nGraph')
    prev_graph_button.pack(side=tk.LEFT)
    next_graph_button.pack(side=tk.LEFT)

    for frame in [main_frame, graph_frame]:
        frame.pack(side=tk.BOTTOM, fill='both')
        frame.pack_propagate(0)

    root.mainloop()

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章