Matplotlib Interactive Event Loops
Solution 1:
The magic is not done by Matplotlib but by IPython, in an actually called magic command.
If you start IPython with ipython --gui=qt
, or type %gui qt
, the Qt event loop will be started and integrated into IPython (the --matplotlib
option does this as well but for the default backend). After that you can just create widgets on the command line without having to start the event loop.
~> ipython
Python 3.5.3 |Continuum Analytics, Inc.| (default, Mar 62017, 12:15:08)
Type'copyright', 'credits'or'license'for more information
IPython 6.1.0 -- An enhanced Interactive Python. Type'?'forhelp.
In [1]: %gui qt
In [2]: from PyQt5 import QtWidgets
In [3]: win = QtWidgets.QPushButton("click me")
In [4]: win.show()
In [5]: win.raise_()
There is a short section on Integrating with GUI event loop that explains how this works under the hood. But just to be clear, you don't have to follow those instructions because event loop integration has already been implemented for Qt. Just use the %gui qt
magic-command.
Update
So indeed you can do this without IPython as well. PyQt makes it possible to have both a regular Python shell and a running event loop simultaneously, as explained in the section on Using PyQt5 from the Python Shell from the PyQt reference guide.
Small difference is that you need to explicitly create the QApplication
yourself. For instance type:
~> python
Python 3.6.0 |Continuum Analytics, Inc.| (default, Dec 232016, 13:19:00)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)] on darwin
Type"help", "copyright", "credits"or"license"for more information.
>>> from PyQt5.QtWidgets import QApplication, QWidget
>>> a = QApplication([])
>>> w = QWidget()
>>> w.show()
>>> w.raise_()
I was wondering how this works with Matplotlib and looked around a bit in the source code of pyplot. It seems to me that Matplotlib can handle both situations. When you execute plt.ion()
a install_repl_displayhook
function is called. Its doc-string says:
Install a repl display hook so that any stale figure are automatically redrawn when control is returned to the repl. This works with IPython terminals and kernels, as well as vanilla python shells.
So, even though IPython is not a dependency of Matplotlib, Matplotlib is aware of IPython and can detect if it is in the IPython shell or in a regular Python shell.
Post a Comment for "Matplotlib Interactive Event Loops"