滑鼠移動和點擊事件#

如何透過連接到移動和點擊事件來與繪圖畫布互動的範例。

注意

此範例練習 Matplotlib 的互動功能,這不會出現在靜態文件中。請在您的電腦上執行此程式碼以查看互動性。

您可以複製並貼上個別部分,或使用頁面底部的連結下載整個範例。

coords demo
import matplotlib.pyplot as plt
import numpy as np

from matplotlib.backend_bases import MouseButton

t = np.arange(0.0, 1.0, 0.01)
s = np.sin(2 * np.pi * t)
fig, ax = plt.subplots()
ax.plot(t, s)


def on_move(event):
    if event.inaxes:
        print(f'data coords {event.xdata} {event.ydata},',
              f'pixel coords {event.x} {event.y}')


def on_click(event):
    if event.button is MouseButton.LEFT:
        print('disconnecting callback')
        plt.disconnect(binding_id)


binding_id = plt.connect('motion_notify_event', on_move)
plt.connect('button_press_event', on_click)

plt.show()

由 Sphinx-Gallery 產生的範例集