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
廣告