Search code examples
pythonmatplotlibcustomtkinter

How do I add a figure to a CustomTkinter Frame using the grid manager?


I'm new to CustomTkinter and trying to add a figure to a Frame. I followed the grid manager tutorial to create this code, and tried to plot a figure in the frame. It runs, but doesn't show the plot, only the frame and the title. what am I missing??

import customtkinter
import tkinter
import matplotlib
matplotlib.use("TkAgg")
from matplotlib.backends.backend_tkagg import (
    FigureCanvasTkAgg, NavigationToolbar2Tk)
from matplotlib.figure import Figure
import numpy as np
customtkinter.set_appearance_mode("dark")  # Modes: "System" (standard), "Dark", "Light"
customtkinter.set_default_color_theme("green")  # Themes: "blue" (standard), "green", "dark-blue"

customtkinter.set_appearance_mode("dark")

class MyFigureFrame(customtkinter.CTkFrame):
    def __init__(self, master, title):
        super().__init__(master)
        self.grid_columnconfigure(0, weight=1)
        # self.x = x
        # self.x = y
        self.title = title

        self.title = customtkinter.CTkLabel(self, text=self.title, fg_color="gray30", corner_radius=6)
        self.title.grid(row=0, column=0, padx=10, pady=(10, 0), sticky="ew")

        fig = Figure()
        t = np.arange(0, 3, .01)
        fig.add_subplot().plot(t, 2 * np.sin(2 * np.pi * t))

        canvas = FigureCanvasTkAgg(fig, self)  # A tk.DrawingArea.
        canvas.draw()

class App(customtkinter.CTk):
    def __init__(self):
        super().__init__()

        self.title("my app")
        self.geometry("400x480")
        self.grid_columnconfigure((0, 1), weight=1)
        self.grid_rowconfigure(0, weight=1)

        self.MyFigureFrame = MyFigureFrame(self, "Figure")
        self.MyFigureFrame.grid(row=0, column=0, padx=10, pady=(10, 0), sticky="nsew")

app = App()
app.mainloop()

Solution

  • The reason why the plot is not displayed within the frame is because the canvas object needs to be added to its frame layout first.

    In the provided code, the canvas object is created but it is not added to the layout of the frame. To add the canvas object to the frame's layout, you can use the grid() method to specify the row and column where the canvas object should be placed.

    To ensure the best possible solution, you can include the following line of code at the end of the MyFigureFrame class. This will add the plot canvas widget to its frame layout:

            canvas.get_tk_widget().grid(row=0, column=0)  # Add canvas to layout