示例代码:
import sys
import matplotlib.pyplot as plt
from PyQt5.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QWidget
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvasclass MyMainWindow(QMainWindow):def __init__(self):super(MyMainWindow, self).__init__()self.initUI()def initUI(self):# 创建Matplotlib图形self.figure, self.ax = plt.subplots()self.canvas = FigureCanvas(self.figure)# 绑定鼠标点击事件self.canvas.mpl_connect('button_press_event', self.on_canvas_click)# 创建主窗口布局central_widget = QWidget()layout = QVBoxLayout(central_widget)layout.addWidget(self.canvas)self.setCentralWidget(central_widget)self.setGeometry(100, 100, 800, 600)self.setWindowTitle('Matplotlib Click Event')self.show()def on_canvas_click(self, event):# 处理鼠标点击事件if event.inaxes is not None:x, y = event.xdata, event.ydataprint(f"Clicked at (x, y) = ({x}, {y})")if __name__ == '__main__':app = QApplication(sys.argv)window = MyMainWindow()sys.exit(app.exec_())
运行结果: