Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีแสดงพิกัดเมาส์ปล่อย (Release) ใน Matplotlib


ภาพรวม

ใช้ Event "button_release_event" เพื่อจับพิกัดเมื่อปล่อยปุ่มเมาส์ รวมถึงปุ่มที่กด (Left/Right/Middle)

ขั้นตอน

  1. ตั้งค่า Figure และ Subplot
  2. พลอตข้อมูลตัวอย่าง
  3. ผูกฟังก์ชัน onclick กับ button_release_event
  4. ใน Callback พิมพ์ event.button, event.xdata, event.ydata
  5. แสดงกราฟ

ตัวอย่างโค้ด

from matplotlib import pyplot as plt

plt.rcParams['backend'] = 'TkAgg'
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

def onclick(event):
    print(event.button, event.xdata, event.ydata)

fig, ax = plt.subplots()
ax.plot(range(10))
fig.canvas.mpl_connect('button_release_event', onclick)
plt.show()

ผลลัพธ์

MouseButton.LEFT 4.961566107601828 1.6644009000562534
MouseButton.LEFT 6.782345894140708 3.7026907931745727
MouseButton.LEFT 2.98552602918754 7.177807987999249

ค่าของ event.button

  • MouseButton.LEFT (1)
  • MouseButton.MIDDLE (2)
  • MouseButton.RIGHT (3)