我正在使用Tkinter构建一个GUI,它将在一个窗口内显示一个动画图形(以及其他一些小部件)。这很好,但第二个matplotlib窗口也随着Tkinter主窗口一起打开。我怎样才能防止这种情况发生?Tkinter打开额外的matplotlib图
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib.figure import Figure
import Tkinter as tk
import ttk
class Application(tk.Frame):
def __init__(self, master=None):
tk.Frame.__init__(self, master)
#self.a = Arduino() #the data is coming in from an arduino
self.createWidgets()
def createWidgets(self):
fig = plt.figure(figsize=(6,6))
ax = fig.add_axes([0,0,1,1])
canvas = FigureCanvasTkAgg(fig, master=root)
canvas.get_tk_widget().place(x=0, y=0)
self.plotbutton=tk.Button(master = root, text="plot", command=lambda: self.plot(canvas,ax))
self.plotbutton.place(x=500, y=0)
self.quitButton = tk.Button(master=root, text="quit", command=self.quit)
self.quitButton.place(x=600, y=0)
def plot(self,canvas,ax):
while(1):
print "plotting"
plt.pause(0.1)
ax.clear() # clear axes from previous plot
#values = self.getData(arduino) #in the full program, I get new theta and r data from an arduino
theta = [0, 1, 2, 3, 4, 5] #arbitrary axis values for testing purposes
r = [0, 1, 2, 3, 4, 5]
ax.plot(r, theta)
plt.xlim([0, 6]) #arbitrary axes limits
plt.ylim([0, 6])
canvas.draw()
def quit(self):
self.master.destroy()
root=tk.Tk()
root.geometry("950x500+300+300")
app=Application(master = root)
app.mainloop()
谢谢!
编辑:使程序进入工作示例
没有一个[MCVE]我只能猜测:我猜,因为你在代码中使用'plt.show()'某处,这将打开一个新窗口。如果你的情节嵌入到tkinter中,你不需要这样做。另外,使用matplotlib的动画功能,你的图形会更光滑。 – Novel
@Novel我没有任何plt.show()在代码:( 我修正了这个例子,因为你建议虽然,也许这将是更有帮助 – janizer