如何通过事件将变量发送到def并返回变量

时间:2018-11-14 16:25:22

标签: python function matplotlib return

如何通过事件发送变量?我希望能够返回被单击的散点图数据点的x,y坐标。目前,该程序可以执行click事件,但是我无法提取x,y数据以供稍后在程序中使用。之后,我添加了一个“坐标”按钮作为使用数据的示例。预先感谢。

import sys
from PyQt5.QtWidgets import QDialog, QApplication, QPushButton, QVBoxLayout
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
import matplotlib.pyplot as plt


def onclick(event):
    ind = event.ind[0]
    data = event.artist.get_offsets()
    xdata, ydata = data[ind,:]
    print ((xdata, ydata))
    return (xdata,ydata)# i want to return these

class Window(QDialog):
    def __init__(self, parent=None):
        super(Window, self).__init__(parent)

        # a figure instance to plot on
        self.figure = plt.figure()

        # this is the Canvas Widget that displays the `figure`
        # it takes the `figure` instance as a parameter to __init__
        self.canvas = FigureCanvas(self.figure)

        # this is the Navigation widget
        # it takes the Canvas widget and a parent
        self.toolbar = NavigationToolbar(self.canvas, self)

        # Just some button connected to `plot` method
        self.button = QPushButton('Plot')
        self.button.clicked.connect(self.plot)
        self.button2 = QPushButton('Coordinate')
        self.button2.clicked.connect(self.coordinate)
        # set the layout
        layout = QVBoxLayout()
        layout.addWidget(self.toolbar)
        layout.addWidget(self.canvas)
        layout.addWidget(self.button)
        layout.addWidget(self.button2)
        self.setLayout(layout)
        self.canvas.mpl_connect('pick_event', onclick)

    def coordinate(self):
        print(xdata, ydata)#these variables are not being returned

    def plot(self):

        x = [10,20,30,40,50]
        y = [100,50,150,200,75]
        size = 100

        # instead of ax.hold(False)
        self.figure.clear()

        # create an axis
        self.axes = self.figure.add_subplot(111)

        # discards the old graph

        self.axes.scatter(x,y,s=size,color='blue', picker=1)
        self.axes.patch.set_facecolor('None')

        # refresh canvas
        self.canvas.draw()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    main = Window()
    main.show()
    sys.exit(app.exec_())

0 个答案:

没有答案