如何修改Python Tkinter代码避免弹出两个窗口?
解决Matplotlib嵌入Tkinter时弹出额外窗口的问题
问题根源在于代码中使用了plt.figure(),该方法会触发Matplotlib默认后端创建独立的Figure窗口。要仅保留Tkinter应用窗口,需直接使用matplotlib.figure.Figure类创建绘图对象,而非依赖pyplot接口。
修改后的完整代码
import tkinter as tk import numpy as np from matplotlib.figure import Figure from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg class Application(tk.Frame): def __init__(self, master): tk.Frame.__init__(self, master) self.createWidgets() def createWidgets(self): # 直接实例化Figure类,不会生成独立窗口 fig = Figure(figsize=(8,8)) ax = fig.add_axes([0.1,0.1,0.8,0.8], polar=True) canvas = FigureCanvasTkAgg(fig, master=root) canvas.get_tk_widget().grid(row=0,column=1) self.plotbutton = tk.Button(master=root, text="plot", command=lambda: self.plot(canvas, ax)) self.plotbutton.grid(row=0, column=0) def plot(self, canvas, ax): c= ['r','b','g'] ax.clear() for i in range(3): theta = np.random.uniform(0,360,10) r = np.random.uniform(0,1,10) ax.plot(theta,r,linestyle="None",marker='o',color=c[i]) canvas.draw() # 移到循环外减少重复绘制开销 root=tk.Tk() app=Application(master=root) app.mainloop()
核心修改说明
- 删除
import matplotlib.pyplot as plt,替换为直接导入from matplotlib.figure import Figure - 将
plt.figure()替换为Figure()实例化,避免触发pyplot的默认窗口创建逻辑 - 优化绘图逻辑:把
canvas.draw()移到循环外部,提升绘制效率
内容的提问来源于stack exchange,提问作者Ted Ersek
相关产品推荐
相关产品推荐

