示例代码:
import sys
import matplotlib.pyplot as plt
from PyQt5.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QWidget
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
class 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.ydata
print(f"Clicked at (x, y) = ({x}, {y})")
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MyMainWindow()
sys.exit(app.exec_())
运行结果: