I am developing a desktop application which, due to complexity I had to break up in different parts. This code simply prints out wether you double clicked or single clicked on the (matplotlib) figure object. A simplified version is as below:
from PyQt5.QtWidgets import QMainWindow, QApplication
import sys
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
class Window(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle('Matplotlib event handling')
self.setGeometry(400, 400, 900, 500)
canvas = Canvas(self, width=8, height=4)
canvas.move(0, 0)
class Canvas(FigureCanvas):
def __init__(self, parent=None, width=5, height=5, dpi=100):
fig = Figure(figsize=(width, height), dpi=dpi)
FigureCanvas.__init__(self, fig)
self.setParent(parent)
fig.canvas.mpl_connect('button_press_event', self.onclick)
self.plot()
def plot(self):
x = [i for i in range(100)]
y = [i**2 for i in range(100)]
ax = self.figure.add_subplot(111)
ax.plot(x,y, color='red')
def onclick(self, event):
if event.dblclick:
print("You doubled clicked...")
else:
print('You single clicked...')
app = QApplication(sys.argv)
window = Window()
window.show()
app.exec()
The program works fine, but if I call the onclick
function from another script, following error arises:
TypeError: onclick() missing 1 required positional argument: 'event'
I understand it has something to do with the scope of the function, but can anybody explain to me what am I doing wrong??
Both the scripts are as follows:
# script1.py
from PyQt5.QtWidgets import QMainWindow, QApplication, QPushButton
import sys
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
from script2 import *
class Window(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle('Matplotlib event handling')
self.setGeometry(400, 400, 900, 500)
canvas = Canvas(self, width=8, height=4)
canvas.move(0, 0)
class Canvas(FigureCanvas):
def __init__(self, parent=None, width=5, height=5, dpi=100):
fig = Figure(figsize=(width, height), dpi=dpi)
FigureCanvas.__init__(self, fig)
self.setParent(parent)
fig.canvas.mpl_connect('button_press_event', onclick(self))
self.plot()
def plot(self):
x = [i for i in range(100)]
y = [i ** 2 for i in range(100)]
ax = self.figure.add_subplot(111)
ax.plot(x, y, color='red')
app = QApplication(sys.argv)
window = Window()
window.show()
app.exec()
And...
# script2.py
def onclick(self, event):
if event.dblclick:
print("You doubled clicked...")
else:
print('You single clicked...')