GUI creation and interaction in IPython


In [ ]:
%gui

In [1]:
from PyQt5 import QtWidgets

In [ ]:
b1 = QtWidgets.QPushButton("Click Me")

A pop up will appear saying

The kernel appears to have died and will restart automatically

In the terminal, you can also see the following message

QWidget: Must construct a QApplication before a QWidget
[I 11:26:36.051 NotebookApp] KernelRestarter: restarting kernel (1/5)
WARNING:root:kernel 08b46e93-bcf2-49ce-af69-0979e879b7e2 restarted

In [1]:
%gui qt5

In [2]:
from PyQt5 import QtWidgets

In [3]:
b1 = QtWidgets.QPushButton("Click Me")

In [4]:
b1.show()


In [5]:
def on_click_cb():
    print("Clicked")

In [6]:
b1.clicked.connect(on_click_cb)


Clicked
Clicked
Clicked

Now, if you click the button, the callback will be called.

And since Jupyter Notebook is awesome the output will be displayed in the cell's output area (Look at the output area for the previous cell!)

Automatic-connection-using-a-new-Qt-Console


In [1]:
%connect_info


{
  "shell_port": 50340,
  "iopub_port": 50341,
  "control_port": 50343,
  "hb_port": 50344,
  "ip": "127.0.0.1",
  "kernel_name": "",
  "signature_scheme": "hmac-sha256",
  "key": "d651e3f1-e8f8-4994-a612-d733e87807b3",
  "stdin_port": 50342,
  "transport": "tcp"
}

Paste the above JSON into a file, and connect with:
    $> jupyter <app> --existing <file>
or, if you are local, you can connect with just:
    $> jupyter <app> --existing kernel-ffc6c842-3184-43af-a538-6b0c85ee0594.json
or even just:
    $> jupyter <app> --existing
if this is the most recent Jupyter kernel you have started.

In [2]:
!jupyter kernel list


Traceback (most recent call last):
  File "E:\Miniconda3\Scripts\jupyter-script.py", line 5, in <module>
    sys.exit(jupyter_core.command.main())
  File "E:\Miniconda3\lib\site-packages\jupyter_core\command.py", line 186, in main
    _execvp(command, sys.argv[1:])
  File "E:\Miniconda3\lib\site-packages\jupyter_core\command.py", line 104, in _execvp
    raise OSError('%r not found' % cmd, errno.ENOENT)
OSError: [Errno 'jupyter-kernel' not found] 2

In [7]:
%qtconsole

Now the Jupyter QtConsole will be started by connecting to the ipython kernel that is already running.

You do not believe it?

Well just type the magic %whos to see the truth.

You can redisplay the button now!!

I prefer continuing to work in the notebook, so I will close the button and also the QtConsole.

Pay close attention to the message in the dialog box.

Back in the Notebook turf, you can redisplay the button and continue clicking.


In [10]:
b1.show()


Clicked
Clicked
Clicked