【发布时间】:2017-08-01 16:47:05
【问题描述】:
我正在使用 Tkinter 构建一个 GUI,它将在窗口中显示动画图形(以及其他一些小部件)。这很好用,但是第二个 matplotlib 窗口也与 Tkinter 主窗口一起打开。我怎样才能防止这种情况发生?
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()
谢谢!
编辑:将程序制作成工作示例
【问题讨论】:
-
没有minimal reproducible example 我只能猜测:我猜是因为您在代码中某处使用了
plt.show(),这会打开一个新窗口。如果您的情节嵌入到 tkinter 中,则不需要它。另外,使用 matplotlib 的动画函数,你的图形会更平滑。 -
@Novel 我在代码中没有任何 plt.show() :( 我按照你的建议修复了这个例子,也许这会更有帮助
标签: python matplotlib tkinter