matplotlib图形不显示在tkinter窗口上

时间:2017-05-17 19:43:38

标签: python-2.7 matplotlib tkinter

当我尝试在tkinter窗口中使用matplotlib绘制图形时,它根本就不会显示出来。如果我删除特定于tkinter的部分,只需执行基本的plt.plot(...)和plt.show(),它就会出现在我的常规文本输出字段中。但是,在这种情况下,我希望它出现在tkinter窗口中。我相信它,因为我在mac(macOS 10.12.4)上运行它,但我无法弄清楚如何让它显示在tkinter窗口中。

import numpy as np
import Tkinter as tk

import matplotlib
matplotlib.use('TkAgg')

from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import matplotlib.pyplot as plt

root = tk.Tk()

fig = plt.figure(1)
t = np.arange(0.0,3.0,0.01)
s = np.sin(np.pi*t)
plt.plot(t,s)

canvas = FigureCanvasTkAgg(fig, master=root)
plot_widget = canvas.get_tk_widget()

def update():
    s = np.cos(np.pi*t)
    plt.plot(t,s)
    plt.show()

plot_widget.grid(row=0, column=0)
tk.Button(root,text="Update",command=update).grid(row=1, column=0)
root.mainloop()

正如我所说,我相信它是因为我在MacOS上运行。另外,当我运行这个空白的tkinter窗口时会显示更新按钮,但没有图表。然而,Graph DOES显示在常规文本输出中,但我希望它在tkinter窗口中用于GUI。请帮助!

1 个答案:

答案 0 :(得分:3)

您需要更新tk画布中已有的数字,而不是显示plt.show()的新数字。在这种情况下,只有一个数字打开,因此plt.plot()实际上会起作用(尽管在更复杂的情况下它可能会失败)。剩下的是在绘图后重绘画布fig.canvas.draw_idle()

import numpy as np
import Tkinter as tk
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import matplotlib.pyplot as plt

root = tk.Tk()

fig = plt.figure(1)
t = np.arange(0.0,3.0,0.01)
s = np.sin(np.pi*t)
plt.plot(t,s)

canvas = FigureCanvasTkAgg(fig, master=root)
plot_widget = canvas.get_tk_widget()

def update():
    s = np.cos(np.pi*t)
    plt.plot(t,s)
    fig.canvas.draw_idle()

plot_widget.grid(row=0, column=0)
tk.Button(root,text="Update",command=update).grid(row=1, column=0)
root.mainloop()

对于未来和保存方面,在将matplotlib嵌入GUI时尽量避免使用pyplot。这可以防止您遇到此处报告的问题。

import numpy as np
import Tkinter as tk
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure

root = tk.Tk()

fig = Figure()
ax = fig.add_subplot(111)
t = np.arange(0.0,3.0,0.01)
s = np.sin(np.pi*t)
ax.plot(t,s)

canvas = FigureCanvasTkAgg(fig, master=root)
plot_widget = canvas.get_tk_widget()

def update():
    s = np.cos(np.pi*t)
    ax.plot(t,s)
    fig.canvas.draw_idle()

plot_widget.grid(row=0, column=0)
tk.Button(root,text="Update",command=update).grid(row=1, column=0)
root.mainloop()