我正在使用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