[Python] tkinter resizes when adding matplotlib to reserverd space

Discussão em 'Python' iniciado por Stack, Março 17, 2025.

  1. Stack

    Stack Membro Participativo

    I have a gui with an empty tk.Canvas widget which I want to fill during runtime with a matplotlib plot. However, when adding the plot, it forces the gui to use the plot size instead of using the provided space, moving stuff around in the gui. What can I do such that the plot is created with the same dimensions as the Canvas?

    MWE:

    import matplotlib as mpl
    mpl.use('TkAgg')

    import tkinter as tk
    from matplotlib import figure
    from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

    root = tk.Tk()

    def show_plot():
    fig = figure.Figure()
    ax=fig.add_subplot()
    ax.scatter([1, 2, 3, 4], [4, 7, 2, 4])
    canv = FigureCanvasTkAgg(fig, canvas)
    canv.draw()
    canv.get_tk_widget().pack(fill=tk.BOTH, expand=1)

    canvas = tk.Canvas(root, width=600, height=600)
    canvas.pack(fill=tk.NONE, expand=0)
    tk.Button(root, text='show plot', command=show_plot).pack()

    root.mainloop()


    I already tried changing the fill and expand parameters in the .pack() calls for both the plot and the canvas but that didn't work.

    Continue reading...

Compartilhe esta Página