1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[Python] Issue with updating plot in tkinter TopLevel using matplotlib FigureCanvasTkAgg

Discussão em 'Python' iniciado por Stack, Outubro 7, 2024 às 11:13.

  1. Stack

    Stack Membro Participativo

    I am trying to use below code to update the plot in matplotlib FigureCanvasTkAgg embedded in tkinter TopLevel window.

    import tkinter as tk
    from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg, NavigationToolbar2Tk)
    from matplotlib.figure import Figure

    def toplevelfunc():
    global fig, ax, canvas
    top = tk.Toplevel()

    ## Widgets (Run Button, Entry Field) to select a file from which graph has to be plotted on canvas
    ## Run button function which passes file to be plotted "plot_data"

    result_frame = tk.Frame(top)
    result_frame.grid(column = 0, row = 3, sticky='NSEW', padx = (15,15), pady = (5, 5), columnspan=3)

    fig = Figure(figsize=(10, 5), dpi=100)
    ax = fig.add_subplot(111)
    fig.subplots_adjust(bottom=0.016, right=0.98, top=0.98, left=0.075, wspace=0, hspace=0)

    ax.set_aspect('auto')
    ax.set(title="",xticks=[], yticks=[])
    ax.spines["top"].set_visible(False)
    ax.spines["right"].set_visible(False)
    ax.spines["left"].set_visible(False)
    ax.spines["bottom"].set_visible(False)

    canvas = FigureCanvasTkAgg(fig, master=result_frame)
    canvas.draw()

    toolbar = NavigationToolbar2Tk(canvas,result_frame)

    toolbar.update()
    toolbar.pack(side=tk.TOP, fill=tk.X, padx=0)

    canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1, padx=10)

    canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=1, padx=5)

    def plot_data(file):
    global fig, ax, canvas
    ax.clear()

    ## Code to plot the file data

    ax.set_aspect('auto')
    # ax.set(title="",xticks=[], yticks=[])
    ax.spines["top"].set_visible(False)
    ax.spines["right"].set_visible(False)
    ax.spines["left"].set_visible(True)
    ax.spines["bottom"].set_visible(True)

    canvas.draw()


    The issue which I am facing is that plot is getting updated in the FigureCanvasTkAgg but it is not occupying the complete canvas area and old plot is not getting cleared because of which I am observing overlapping plots.

    Can someone let me know how to resolve it.

    Continue reading...

Compartilhe esta Página