没有放入tkinter之前的代码如下:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
from matplotlib.backend_bases import key_press_handler
from matplotlib.figure import Figure
from matplotlib.widgets import Cursor # 处理鼠标
f = plt.figure(figsize=(5, 4), dpi=100)
a = f.add_subplot(111) # 添加子图:1行1列第1个
x = np.arange(0, 3, 0.01)
y = np.sin(2 * np.pi * x)
a.plot(x, y) # 在前面得到的子图上绘图
cursor = Cursor(a, useblit=True, color='red', linewidth=0.5, linestyle='--')
plt.show()
运行后的界面如下是有十字光标的
但是把这个放入tkinter之后,光标不见了,这是怎么回事,请有懂的朋友指点一下,放入tkinter的代码和运行图片如下:
import tkinter
import numpy as np
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
from matplotlib.backend_bases import key_press_handler
from matplotlib.figure import Figure
from matplotlib.widgets import Cursor # 处理鼠标
root = tkinter.Tk() # 创建tkinter的主窗口
root.title("在tkinter中使用matplotlib")
f = Figure(figsize=(5, 4), dpi=100)
a = f.add_subplot(111) # 添加子图:1行1列第1个
x = np.arange(0, 3, 0.01)
y = np.sin(2 * np.pi * x)
a.plot(x, y)
cursor = Cursor(a, useblit=True, color='w', linewidth=0.5, linestyle='--') # 将绘制的图形显示到tkinter:创建属于root的canvas画布,并将图f置于画布上
canvas = FigureCanvasTkAgg(f, master=root)
canvas.draw()
canvas.get_tk_widget().pack(side=tkinter.TOP, # 上对齐
fill=tkinter.BOTH, # 填充方式
expand=tkinter.YES) # 随窗口大小调整而调整
# 主循环
root.mainloop()