Issue
I'm trying to learn PySide for a project I'm working on. I'm working through the Zetcode tutorials, but from the very beginning I'm running problems. I am writing and running my code through Enthought's Canopy. When I run the code from the command line it works fine. This question may be related to my issue, however no answer is given there.
When I use the simplest code from the tutorial
import sys
from PySide import QtGui
wid = QtGui.QWidget()
wid.resize(250, 150)
wid.setWindowTitle('Simple')
wid.show()
everything runs correctly. The next example does more or less the same, except from an OOP perspective.
import sys
from PySide import QtGui
class Example(QtGui.QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
self.setGeometry(300, 300, 250, 150)
self.setWindowTitle('Icon')
self.setWindowIcon(QtGui.QIcon('web.png'))
self.show()
def main():
ex = Example()
if __name__ == '__main__':
main()
When run the program flashes (I can see the window appear for a brief second) and then closes. Raising an exception before the end of main()
will keep the window on the screen.
TL;DR
Why does putting the program in a class make it not work?
Solution
The difference between the two examples, is that first one keeps a reference to the widget as a global variable, whilst the second creates a local variable that gets garbage-collected when it goes out of scope (i.e. when the function returns).
The simplest way to fix this, is to make the ex
variable global, like this:
def main():
global ex
ex = Example()
or you could just get rid of the main
function, and simply do:
if __name__ == '__main__':
ex = Example()
Answered By - ekhumoro
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.