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

无法在CustomTk中通过Matplotlib嵌入NetworkX图形

问题分析与解决

你的代码核心问题是图形绘制到了Matplotlib的默认临时画布,而非绑定到CustomTk的Figure对象,同时存在重复创建Figure、混用pyplot与面向对象接口的问题,导致GUI画布空白。

具体问题点

  1. 调用nx.draw_networkx()时,没有指定绘制目标轴(ax),默认绘制到Matplotlib自动创建的临时Figure上,而非你后续绑定到Tk的fig对象。
  2. 你在绘制图形后又重新创建了fig = Figure(figsize=(10, 10), dpi=100),直接覆盖了之前的Figure,新的空Figure自然没有内容。
  3. 混用plt.gca()等pyplot接口与面向对象的Figure/ax,造成上下文混乱;plt.show()会弹出独立窗口,对GUI嵌入无意义,反而干扰。

修正后的代码

import tkinter
import customtkinter
import networkx as nx

from matplotlib.backends.backend_tkagg import (
    FigureCanvasTkAgg, NavigationToolbar2Tk)
from matplotlib.backend_bases import key_press_handler
from matplotlib.figure import Figure
import matplotlib.pyplot as plt

root = customtkinter.CTk()
root.title("Embedding in Tk")

# 创建绑定到GUI的Figure和轴
fig = Figure(figsize=(10, 10), dpi=100)
ax = fig.add_subplot(111)
plt.style.use('ggplot')

# 生成图并指定绘制到创建的ax上
G = nx.random_geometric_graph(20, 0.125, seed=896803)
nx.draw_networkx(G, pos=nx.circular_layout(G), node_size=4000, with_labels=True, font_size=20, ax=ax)

# 调整轴样式
ax.margins(0.11)
fig.tight_layout()
ax.axis("off")

# 创建画布并绑定到GUI
canvas = FigureCanvasTkAgg(fig, master=root)
canvas.draw()
canvas.get_tk_widget().pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1)

# 添加工具栏
toolbar = NavigationToolbar2Tk(canvas, root)
toolbar.update()

# 按键事件处理
def on_key_press(event):
    print("you pressed {}".format(event.key))
    key_press_handler(event, canvas, toolbar)

canvas.mpl_connect("key_press_event", on_key_press)

# 退出按钮
def _quit():
    root.quit()
    root.destroy()

button = customtkinter.CTkButton(master=root, text="Quit", command=_quit)
button.pack(side=tkinter.BOTTOM)

root.mainloop()

关键修改说明

  • 先创建fig和ax,再调用nx.draw_networkx()时通过ax=ax参数指定绘制目标,确保图形画在绑定到GUI的画布上。
  • 移除重复创建fig的代码,避免覆盖已有内容。
  • 用fig.tight_layout()替代plt.tight_layout(),保持面向对象接口的一致性。
  • 移除plt.show(),不再弹出独立窗口。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 07:25:14