Issue
When I execute my PyQt script in Spyder, it doesn't seem to do anything except clearing variables. When I execute it again, it works as expected.
As you can see below, I cannot reduce the code any further, but the problem remains unchanged. Is this the expected behaviour? What am I doing wrong?
import sys
from PyQt5 import QtWidgets
app = QtWidgets.QApplication(sys.argv)
window = QtWidgets.QMainWindow()
window.show()
app.exec_()
In detail:
- I open Spyder.
- I execute the script. A window opens and I terminate by closing the window (expected behaviour).
- I execute the script. After a few seconds, the console returns. Nothing seems to have happened except that the variables are gone (unexpected behaviour).
- Repeat from 2...
Solution
The problem isn't so much that the variables are being cleared, but rather that the PyQt application cannot be run repeatedly within Spyder. It's a common issue that is addressed in the Spyder Wiki: How to run PyQt applications within Spyder.
It seems to be tied to the fact that Spyder is itself a Qt application. Specifically, the Wiki entry has this by way of an explanation:
The most common problem when running a PyQt application multiple times inside Spyder is that a QApplication instance remains in the namespace of the IPython console kernel after the first run. In other words, when you try to re-run your application, you already have a QApplication instance initialized.
The work-around is to make sure that the QApplication
instance goes out of scope when your script exits, i.e., create it within the scope of a function. Using the simple example from above, it just comes down to this:
import sys
from PyQt5 import QtWidgets
def main():
app = QtWidgets.QApplication(sys.argv)
window = QtWidgets.QMainWindow()
window.show()
app.exec_()
main()
Answered By - john-hen
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.