import sys import tkinter as Tk import matplotilib from numpy import arange,sin,pi from matplotlib.backends,backend_tkagg import FigureCanvasTkAgg,NavigationToolbar2TkAgg from matplotlib.figure import Figure matplotlib.use('TkAgg') root=Tk.Tk() root.title("我们测试-matplotlib in Tk") #设置图形尺寸和质量 f=Figure(figsize=(5,4),dpi=100) a=f.add_subplot(111) t=arange(0.0,3,0.01) s=sin(2*pi*t) #绘制图形 a.plot(t.s) #吧绘制的图形显示到tkinter窗口上 canvas=FigureCanvasTkAgg(f,master=root) canvas.show() canvas.get_tk_widget().pack(side=Tk.TOP,fill=Tk.BOTH,expand=1) #把matplotlib绘制图形的导航工具栏显示到tkinter窗口上 toolbar=NavigationToolbar2TkAgg(canvas,root) toolbar.update() canvas._tkcanvas.pack(side=Tk.TOP,fill=Tk.BOTH,expand=1) #定义并绑定键盘事件处理函数 def on_key_event(event): print('you pressed %s'% event.keys) key_press_handler(event,canvas,toolbar) canvas.mpl_connect('key_press_event',on_key_event) #按钮单击事件处理函数 def quit(): root.quit() root.destroy() button=Tk.Button(master=root,text='Quit',command=quit) button=pack(side=Tk.BOTTOM) Tk.mainloop()
时间: 2024-04-11 22:27:33 浏览: 166
这段代码中有一些错误和拼写错误。首先,`matplotlib.backends` 应该是 `matplotlib.backends.backend_tkagg`。然后,`plot` 函数应该是 `plot(t, s)` 而不是 `plot(t.s)`。此外,在调用 `button.pack(side=Tk.BOTTOM)` 之前,应该是 `button.pack(side=Tk.BOTTOM)` 而不是 `button=pack(side=Tk.BOTTOM)`。以下是修改后的代码:
```python
import sys
import tkinter as Tk
import matplotlib
from numpy import arange, sin, pi
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib.figure import Figure
matplotlib.use('TkAgg')
root = Tk.Tk()
root.title("我们测试-matplotlib in Tk")
# 设置图形尺寸和质量
f = Figure(figsize=(5, 4), dpi=100)
a = f.add_subplot(111)
t = arange(0.0, 3, 0.01)
s = sin(2 * pi * t)
# 绘制图形
a.plot(t, s)
# 把绘制的图形显示到tkinter窗口上
canvas = FigureCanvasTkAgg(f, master=root)
canvas.show()
canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)
# 把matplotlib绘制图形的导航工具栏显示到tkinter窗口上
toolbar = NavigationToolbar2TkAgg(canvas, root)
toolbar.update()
canvas._tkcanvas.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)
# 定义并绑定键盘事件处理函数
def on_key_event(event):
print('you pressed %s' % event.keys)
key_press_handler(event, canvas, toolbar)
canvas.mpl_connect('key_press_event', on_key_event)
# 按钮单击事件处理函数
def quit():
root.quit()
root.destroy()
button = Tk.Button(master=root, text='Quit', command=quit)
button.pack(side=Tk.BOTTOM)
Tk.mainloop()
```
阅读全文