3

I am trying to learn how to use pyqtgraph and tried to run the following first simple example given in the above document:

#!/usr/bin/env python3

import pyqtgraph as pg

import numpy as np

x = np.random.normal(size=1000)

y = np.random.normal(size=1000)

pg.plot(x,y,pen=None,symbol='o',title='first graph')

I am using python 3.5.3 on a Raspberry Pi 3 with Raspbian Stretch.

If I run the above program in Thonny or IDLE, the program runs without any error but does not display any output.

Similarly, if I run the program at the Linux command prompt by simply calling the program name (I have made it executable using chmod +x) or by typing python3 followed by the program name, still it does not show anything.

However, if I type python3 at the Linux prompt and get a python prompt and then run each of the lines in the program one by one, then it displays a scatter plot in a window titled "first graph" as expected.

Can someone please let me know what I need to do to get the code to display the graph when run through the Thonny or IDLE or by calling it as a program?

Thank you.

Robert
  • 7,394
  • 40
  • 45
  • 64
Ajith
  • 63
  • 1
  • 7
  • Does this answer your question? [PyQtGraph opening then closing straight away](https://stackoverflow.com/questions/44632018/pyqtgraph-opening-then-closing-straight-away) – user202729 Feb 25 '21 at 07:37

1 Answers1

6

Every GUI needs an event loop, and in your case you are not creating it, in the following code I show how to do it:

#!/usr/bin/env python3

import pyqtgraph as pg
from pyqtgraph.Qt import QtCore, QtGui
import numpy as np


x = np.random.normal(size=1000)
y = np.random.normal(size=1000)
pg.plot(x,y,pen=None,symbol='o',title='first graph')


if __name__ == '__main__':
    import sys
    if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
        QtGui.QApplication.instance().exec_()

enter image description here

Note: do not use any IDE since many can not handle the event loop correctly, execute it from the terminal.

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
  • Since IDLE runs user code in a separate process, with `sys.flags.interactive` == 0, and no tk/tkinter event loop running, I expect this code to run. If not, I would like to know. – Terry Jan Reedy Oct 23 '18 at 13:55
  • @TerryJanReedy Not only do I say it for that, another point is that when an application breaks the IDE many times it throws an error code instead of the message so I prefer to run it in the terminal. – eyllanesc Oct 23 '18 at 15:21
  • One reason IDLE runs user code in a separate process is so that user code cannot accidentally crash the IDE. Ajith, if you try running the above from an IDLE editor, I would like to know the result. – Terry Jan Reedy Oct 24 '18 at 16:00