You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决使用grid管理器向CustomTkinter Frame添加图表不显示的问题?

问题原因及解决办法

你的代码已经正确创建了matplotlib图表和canvas,但没有将canvas添加到CTkFrame的布局系统中,同时Frame内部的行权重未配置,导致图表没有显示空间。

需要修改的几个关键点:

  • 给MyFigureFrame的第1行配置权重,让图表区域能自动填充剩余空间
  • 将创建好的canvas通过grid方法添加到Frame中
  • 优化变量命名,避免参数被覆盖

修改后的完整代码:

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")
customtkinter.set_default_color_theme("green")

class MyFigureFrame(customtkinter.CTkFrame):
    def __init__(self, master, title):
        super().__init__(master)
        # 配置列0和行1的权重,让标题与图表区域自适应空间
        self.grid_columnconfigure(0, weight=1)
        self.grid_rowconfigure(1, weight=1)

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

        fig = Figure(dpi=100)  # 指定dpi提升图表清晰度
        t = np.arange(0, 3, .01)
        fig.add_subplot().plot(t, 2 * np.sin(2 * np.pi * t))

        canvas = FigureCanvasTkAgg(fig, self)
        canvas.draw()
        # 将canvas组件添加到grid布局,占满整个单元格
        canvas.get_tk_widget().grid(row=1, column=0, padx=10, pady=(10, 10), sticky="nsew")

        # 可选:添加matplotlib导航工具栏,支持缩放、保存等操作
        toolbar = NavigationToolbar2Tk(canvas, self)
        toolbar.update()
        toolbar.grid(row=2, column=0, padx=10, pady=(0,10), sticky="ew")

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

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

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

app = App()
app.mainloop()

关键修改说明:

  1. 配置行权重:添加self.grid_rowconfigure(1, weight=1),让图表所在行能占据Frame的剩余空间
  2. 挂载canvas到布局:调用canvas.get_tk_widget().grid(...)将matplotlib的canvas组件添加到CTkFrame中,sticky="nsew"确保它填满整个单元格
  3. 修正变量名:将self.title改为self.title_label,避免覆盖初始化时传入的title参数
  4. 可选工具栏:添加导航工具栏增强图表交互性,不需要可直接删除相关代码

内容的提问来源于stack exchange,提问作者Miri

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 07:14:56