按鍵事件#

示範如何連接到按鍵事件。

注意

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

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

Press a key
import sys

import matplotlib.pyplot as plt
import numpy as np


def on_press(event):
    print('press', event.key)
    sys.stdout.flush()
    if event.key == 'x':
        visible = xl.get_visible()
        xl.set_visible(not visible)
        fig.canvas.draw()


# Fixing random state for reproducibility
np.random.seed(19680801)

fig, ax = plt.subplots()

fig.canvas.mpl_connect('key_press_event', on_press)

ax.plot(np.random.rand(12), np.random.rand(12), 'go')
xl = ax.set_xlabel('easy come, easy go')
ax.set_title('Press a key')
plt.show()

由 Sphinx-Gallery 產生的圖庫