Python库matplotlib之十
- 事件处理
- 关闭活动
- 鼠标移动和点击事件
- 按键事件
事件处理
关闭活动
下列代码,当用户点击关闭窗口时,调用关闭回调函数on_close。这给程序员在窗口关闭之前,做一些cleanup工作, 比如,关闭文件,TCP/IP端口等。
import matplotlib.pyplot as plt
import pandas as pd
import numpy as npdelta = 0def on_close(event):print('Closed Figure!')def update_draw(axes):global x, y, deltay = np.sin(x + delta)line.set_ydata(y)axes.figure.canvas.draw()delta += 10if __name__ == "__main__":global x, yfig, ax = plt.subplots()fig.canvas.mpl_connect('close_event', on_close)x = np.linspace(0, 10 * np.pi, 100)y = np.sin(x)line, = plt.plot(x, y);timer = fig.canvas.new_timer(interval=100)timer.add_callback(update_draw, ax)timer.start()plt.show()
程序运行输出屏幕
C:\>python event_handle_1.py
Closed Figure!
鼠标移动和点击事件
下列的例子通过连接移动和单击事件与绘图画布进行交互的例子。
下列运行时,当用户点击鼠标的左键,一条竖线随鼠标移动;当用户点击右键时,竖线停止移动。再次点击左键,竖线再次随鼠标移动。
import matplotlib.pyplot as plt
import numpy as npfrom matplotlib.backend_bases import MouseButtondef on_move(event):global fig, ax, t, sif event.inaxes:ax.clear()x = [event.xdata, event.xdata]y = [0, event.ydata]ax.plot(x, y)line, = ax.plot(t, s)fig.canvas.draw()def on_click(event):global binding_idif event.button is MouseButton.LEFT:print('disconnecting callback')plt.disconnect(binding_id)elif event.button is MouseButton.RIGHT:print('connecting callback')binding_id = plt.connect('motion_notify_event', on_move)if __name__ == "__main__":global fig, ax, t, s, binding_idt = np.arange(0.0, 1.0, 0.01)s = np.sin(2 * np.pi * t)fig, ax = plt.subplots()line, = ax.plot(t, s)binding_id = plt.connect('motion_notify_event', on_move)plt.connect('button_press_event', on_click)plt.show()
程序运行屏幕输出
C:\>python event_handle_2.py
disconnecting callback
connecting callback
disconnecting callback
connecting callback
disconnecting callback
connecting callback
disconnecting callback
connecting callback
disconnecting callback

按键事件
下列程序检测四个键x,y,+ 和 -。x和y改变正弦曲线的画线方式和颜色, +和-改变正弦曲线的相位角。
import sys
import matplotlib.pyplot as plt
import numpy as npx = np.linspace(0, 10 * np.pi, 100)
y = np.sin(x)linestyle = ["-.","-", ":"]
colors = ["b","r","g"]
linestyle_ndx = 0
delta = 0
color_ndx = 0def on_press(event):global linestyle, linestyle_ndx, line, x, y, delta, ax, color_ndxif event.key == 'x':line.set_linestyle(linestyle[linestyle_ndx])y = np.sin(x+delta)line.set_ydata(y)linestyle_ndx += 1if linestyle_ndx >= len(linestyle):linestyle_ndx = 0fig.canvas.draw()if event.key == 'y':line.set_color(colors[color_ndx])y = np.sin(x+delta)line.set_ydata(y)color_ndx += 1if color_ndx >= len(colors):color_ndx = 0fig.canvas.draw()elif event.key == '+':delta += 10y = np.sin(x+delta)line.set_ydata(y)ax.set_xlabel('delta = ' + str(delta))fig.canvas.draw()elif event.key == '-':delta -= 10if delta < 0:delta = 0y = np.sin(x+delta)line.set_ydata(y)fig.canvas.draw()xl = ax.set_xlabel('delta = ' + str(delta))fig.canvas.draw()if __name__ == "__main__":# Fixing random state for reproducibilityglobal fig, ax, linefig, ax = plt.subplots()fig.canvas.mpl_connect('key_press_event', on_press)#line, = ax.plot(x, y, linestyle[linestyle_ndx])line, = ax.plot(x, y, 'b-.')ax.set_title('Press X')plt.show()

