无法在CustomTk中通过Matplotlib嵌入NetworkX图形
问题分析与解决
你的代码核心问题是图形绘制到了Matplotlib的默认临时画布,而非绑定到CustomTk的Figure对象,同时存在重复创建Figure、混用pyplot与面向对象接口的问题,导致GUI画布空白。
具体问题点
- 调用
nx.draw_networkx()时,没有指定绘制目标轴(ax),默认绘制到Matplotlib自动创建的临时Figure上,而非你后续绑定到Tk的fig对象。 - 你在绘制图形后又重新创建了
fig = Figure(figsize=(10, 10), dpi=100),直接覆盖了之前的Figure,新的空Figure自然没有内容。 - 混用
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
相关产品推荐
相关产品推荐

