PyQt5 Display Issue - pyqt5

I've asked pretty much the same question here before (I've since deleted it after getting no solutions), but one peculiarity has arose since then.
The following program:
import sys
from PyQt5 import QtWidgets, QtGui, QtCore
app = QtWidgets.QApplication([])
w = QtWidgets.QWidget()
w.setWindowTitle('Test')
w.show()
sys.exit(app.exec_())
does not produce a window, generates no errors, and continues to run until forcefully terminated. However, the same code does produce a window in the interactive interpreter.
I have repaired python; uninstalled, reinstalled, upgraded, and downgraded both python and PyQt including PyQt's other versions, as well as the dependencies any PyQt version requires. I am at a total loss as to what/where the problem is, especially since PyQt5 had worked properly before on the same machine.
Any help in fixing this would be immensely appreciated.

Related

Tensorflow "decode_png" keeps printing "Cleanup called..."

I'm using tensorflow to open some .png images and every image it opens, an annoying message is printed.
def open_img(path):
img = tf.io.read_file(path)
img = tf.io.decode_png(img)
return tf.image.resize(img, [IMG_HEIGHT, IMG_WIDTH])
Every time i try to open an image it says "Cleanup called...", even while training:
(This code is running on Kaggle)
tensorflow version: 2.6.3
How can i solve this annoying thing please?
Updating my TensorFlow installation to version 2.8 fixed the issue for me.
If you're running the code on Kaggle, upgrading Tensorflow to 2.8 will break CuDNN dependencies for GPU. I found that downgrading Tensorflow to 2.4.1 one will remove the debugging message while being able to work with GPU.
I believe, these "Cleanup called..." lines might be generated by some C++ code running under the hood of TF, as I was not able to redirect them to a file using redirect_stdout(). Technically, it would be best to intercept those lines and just not output them or dump them to smth like /dev/null. E.g., here, Eli Bendersky showcases how to redirect C-level output, but in my case it didn't work out with Python 3.7. Perhaps, Eli's code needs adjustment for a Python version newer than 3.4.
Concerning the given answers with upgrading/downgrading, this likely won't work with committed Kaggle notebooks as, I believe, there is no way to restart the kernel once the notebook is committed.
For committed Kaggle notebooks, there is the following workaround w/o upgrading/downgrading anything: if you need to view the output of a cell that produces "Cleanup called…" later, log it to a file or both to a file and the console (here's a code snippet for doing so), and invoke the following code at the end of the cell:
from IPython.display import clear_output
clear_output()
This will clear the output of that cell so that, once you open the "Notebook" tab of the committed notebook after it's been finished, it won't be littered with "Cleanup called…" lines and, as such, will open swiftly. Simple logging to a file (like in the above linked snipped) will not capture "Cleanup called…" lines, so one will be able to view the entire log of that cell in that log file in the "Data" tab of the committed notebook. The "Logs" tab, sadly, will still be cluttered with "Cleanup called…" lines.

Cannot use matplotlib library?

I am getting a weird error when calling any function with matplotlib.
import matplotlib as plt
plt.bar(np.arange(7, [1,3,2,1,4,6,1])
I get this error:
IPython.core.display.Javascript object
IPython.core.display.HTML object
Traceback (most recent call last): self.kernel.session.send(self.kernel.iopub_socket, msg_type,*
**AttributeError: 'NoneType' object has no attribute 'session'**
I have already tried:
upgrade my pip
upgrade matplotlib
installing pyplot (which brings error --> Non-zero exit code (1) --> Could not find a version that satisfies the requirement pyplot (from versions: ) No matching distribution found for pyplot)
My Matplotlib version = 3.3.3
OS --> Windows 10
Nothing seems to work and I am stuck. Do you have any idea why this is?
You are importing wrongly the library.
Usually one use
import matplotlib as mpl
(seldom used) or
import matplotlib.pyplot as plt
You are mixing the two imports/names, and so also the interface. Use the second import I wrote, for plt (pyplot).
Ho to debug? When you gain experience, you will learn that usually the problems are in your code and not on environment. So stop upgrading/reinstalling (often you worse the situation, see this site for examples). So try to debug your code. Check the matplotlib page of bar plots. Copy example, modify little things until you have your expected code. (Usually with such steps you find the error).

Debugging FuncAnimation

Consider
def animate(k):
# do stuff, update plots
anm = FuncAnimation(myFig, animate, interval=1, repeat=False)
Why is it not possible to debug anything inside animate?
I can run the same code without visualization in barebones Python and perfectly debug it, but somehow FuncAnimation is totally "opaque".
My IDE is Spyder 4.0.1
UPDATE
I am still struggling to debug FuncAnimation.
Does anyone know how to do that?
I can't see what's happening inside animate.

Using matplotlib with Qt5 backend with an existing QApplication running, in the same process

We have a Qt5 application that uses PySide2. Recently, we wanted to show plots using matplotlib while our PySide2 application is running in the same process (in a different thread) but then matplotlib crashes (when using PySide2) or freezes before drawing (when using PyQt5).
Here is a minimal sample, uncomment the 23rd line to make matplotlib crash or freeze:
from threading import Thread
from PySide2.QtWidgets import QApplication, QLabel
import matplotlib
matplotlib.use('QT5Agg')
import matplotlib.pyplot as plt
def start_qt_app():
t = Thread(target=qt_app_thread_func)
t.start()
def qt_app_thread_func():
app = QApplication()
label = QLabel("Hello World")
label.show()
app.exec_()
# Uncomment the line below to make matplotlib crash.
#start_qt_app()
plt.plot([1, 2, 3, 4])
plt.show()
input("Press enter to quit.")
print("Finished.")
My guess is that this is related to the limitation that we can only have 1 QApplication running in a process. So this causes something to go wrong in matplotlib.
How can I solve this problem? One solution that comes to my mind is to create a proxy object for matplotlib that runs matplotlib in another process but I am not sure if this would be the least labor intensive solution. Maybe I can somehow make matplotlib use the existing QApplication? I cannot run our PySide2 app in another process since it uses dynamically created numpy arrays to be passed from main thread to the GUI, and it would cost performance to start it in another process.
As #ImportanceOfBeingErnest points out, matplotlib can live with Qt as the official example shows: Embedding in Qt.
Example:
from PySide2.QtWidgets import QApplication, QLabel
import matplotlib
matplotlib.use('QT5Agg')
from matplotlib.backends.backend_qt5agg import FigureCanvas
from matplotlib.figure import Figure
if __name__ == '__main__':
app = QApplication()
label = QLabel("Hello World")
label.show()
canvas = FigureCanvas(Figure(figsize=(5, 3)))
ax = canvas.figure.subplots()
ax.plot([1, 2, 3, 4])
canvas.show()
app.exec_()
you should use asyncqt to manage ui and application threads.from asyncqt QEventLoop is a way you can accomplish with
await loop.run_in_executor(exec, method_name)
asyncqt is a spin off library from quamash which is written for PyQt5. example codes are same. So upon your preference, you may use asyncqt with PySide2 or quamash with PyQt5 to make your app responsive when background tasks are running.
asyncqt examples
asyncqt 0.7.0 pypi
Quamash 0.6.1

Error getting PySide to work with matplotlib

I am trying to make PySide work with matplotlib, and I have the same problem
described in this thread
Getting PySide to work with matplotlib
trying to launch the PySide + matplotlib example from
http://wiki.scipy.org/Cookbook/Matplotlib/PySide
I have got an error
win.setCentralWidget(canvas)
TypeError: 'PySide.QtGui.QMainWindow.setCentralWidget' called with wrong argument types:
PySide.QtGui.QMainWindow.setCentralWidget(FigureCanvasQTAgg)
Supported signatures:
PySide.QtGui.QMainWindow.setCentralWidget(PySide.QtGui.QWidget)
Adding of
matplotlib.rcParams['backend.qt4']='PySide'
did not help as well as
os.environ["QT_API"] = "pyside"
At the same time PyQt4 examples work.
I use Windows 7, and WinPython 2.7.5.1 (Python 2.7.5, PySide 1.1.2, matplotlib 1.2.1)
Thank you for help!
The problem was in Spyder.
Everything works in other python dev enviroments.
Jed post the solution on another thread just the next day after my question https://stackoverflow.com/a/17376655/2531821