如何正确地从Tkinter fram中删除图形

2024-10-05 14:28:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我有几个图表,我想显示在一个按钮按下。为此,我将plt.FigureFigureCanvasTkAgg变量设为全局变量,每次按ax.clear()按钮时只需擦除轴。之后,我使用Figure.canvas.mpl_connect添加了一个特性:当我按下图形区域时,第二个点用垂直线高亮显示。当我打印一些简单的输出时(在我的例子中,print('Vertical Line Constructed')select_trade_with_mouse函数中),结果是为每个被构造和擦除的图形创建了事件:当我生成一个图形并按下graph(生成事件)时,print('Vertical Line Constructed')只执行一次。如果生成第二个图并单击graph,那么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()

Tags: import图形dataindexlinebuttonpltax
1条回答
网友
1楼 · 发布于 2024-10-05 14:28:35

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

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

我在开始时创建全局变量click_id = None,然后在construct_graph()中删除前面的click_id,如果它不是None。这样,图形只分配了一个函数

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()

相关问题 更多 >