Question

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?

Was it helpful?

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()

OTHER TIPS

The difference between running in and out of Canopy is that Canopy uses IPython QTConsole running, by default, in pylab mode with a QT GUI backend. The nice thing about this (and one of the many geniuses of ipython) is that you can have a live interaction between the command prompt and your GUI).

I suspect that you are bumping into pylab. A sophisticated program like Matplotlib can figure out whether the GUI event loop was already started, and adapt accordingly. But for your purpose, you probably just want to disable pylab mode, so that the IPython in Canopy acts more like a generic python. To do this, disable Pylab mode from the Canopy Preference menu (Python tab).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top