Matplotlib - 按键事件



在计算机编程中,检测和处理按键事件对于捕获用户输入并在应用程序中启用各种功能至关重要。无论是浏览菜单、输入文本、触发操作还是控制交互式元素,按键事件都在用户交互中扮演着关键角色。

Matplotlib 提供了处理按键事件的工具,允许您在交互式绘图会话中捕获和响应键盘输入。当按下键时,Matplotlib 会触发key_press_event,允许用户根据按下的键定义自定义操作。

该库默认附加了一些按键回调以增强交互性。这些默认回调在 Matplotlib 文档的“导航键盘快捷键”部分中有说明。

示例

让我们来看这个基本的示例,它演示了 Matplotlib 中默认的按键事件。

import numpy as np
import matplotlib.pyplot as plt

# Define a function to handle keypress events
def press(event):
   print('You pressed:', event.key)

# Create a Matplotlib figure and axis
fig, ax = plt.subplots()

# Connect the keypress event handler to the figure canvas
cid = fig.canvas.mpl_connect('key_press_event', press)

# Plot sin wave	
x = np.linspace(0, 10, 100)
ax.plot(x, np.sin(x))

# Display the plot
plt.show()

输出

执行上述程序后,您将获得以下图形,然后按任意键观察此示例的工作方式:

keypress_event_ex1
You pressed: tab
You pressed: caps_lock
You pressed: shift
You pressed: control
You pressed: alt
You pressed: meta
You pressed: a
You pressed: b
You pressed: c
You pressed: d
You pressed: s
You pressed: g
You pressed: g
You pressed: g
You pressed: g
You pressed: k
You pressed: k
You pressed: k
You pressed: k
You pressed: k
You pressed: k
You pressed: l
You pressed: l
You pressed: p
You pressed: p
You pressed: q

观看下面的视频,了解此按键事件功能在此处如何工作。

keypress_event_ex1 gif

从以上输出中,您可以观察到一些默认键的工作方式,例如“g”(切换网格),“s”(保存图形),“q”(关闭图形)等等。

创建自定义按键事件函数

要根据特定需求处理按键事件,您可以创建一个自定义函数,并使用mpl_connect方法将其连接到key_press_event

示例

以下示例演示了一个简单的按键事件函数,当按下“x”键时,该函数会切换 x 轴标签的可见性。

import sys
import matplotlib.pyplot as plt
import numpy as np

def on_press(event):
   print('Pressed key:', event.key)
   sys.stdout.flush()

   # Toggle visibility of xlabel when 'x' key is pressed
   if event.key == 'x':
      visible = xl.get_visible()
      xl.set_visible(not visible)
      fig.canvas.draw()

fig, ax = plt.subplots()
fig.canvas.mpl_connect('key_press_event', on_press)

# Plot random data points
ax.plot(np.random.rand(12), np.random.rand(12), 'go')
xl = ax.set_xlabel('Toggle this label  when the "x" key is pressed', 
   fontsize=16, color='red')
ax.set_title('Press x key')

plt.show()

输出

执行上述程序后,您将获得以下图形,然后按任意键观察此示例的工作方式:

keypress_event_ex2
Pressed key: x
Pressed key: x
Pressed key: x
Pressed key: x
Pressed key: a
Pressed key: enter

观看下面的视频,了解此按键事件功能在此处如何工作。

keypress_event_ex2 gif

示例

这是另一个示例,它演示了如何添加Esc键以退出图形(除了“q”键之外),并计算Enter键被按下的次数。

import numpy as np
import matplotlib.pyplot as plt

# Define a function to handle keypress events
def press(event):
   print('Pressed key:', event.key)
    
   # If the 'enter' key is pressed, append 1 to the count list
   if event.key == 'enter':
      cnt.append(1)
    
   # If the 'escape' key is pressed, close the plot
   if event.key == "escape":
      plt.close()

cnt = []

# Create a figure 
fig, ax = plt.subplots()

# Connect the keypress event handler to the figure canvas
fig.canvas.mpl_connect('key_press_event', press)
ax.plot(np.random.rand(12), np.random.rand(12), 'go')
plt.show()

# Calculate and print the sum of counts
result = sum(cnt)
print(result, cnt)

输出

执行上述程序后,您将获得以下图形,然后按任意键观察此示例的工作方式:

keypress_event_ex3
Pressed key: b
Pressed key: enter
Pressed key: enter
Pressed key: caps_lock
Pressed key: caps_lock
Pressed key: enter
Pressed key: escape
3 [1, 1, 1]
keypress_event_ex3 gif
广告