This is meant to be a comprehensive guide on how to get started coding a cross platform GUI application using python.

For achieving this we will use Eclipse with the plug-in PyDev and PyQT which is python bindings for the cross platform UI framework QT. My aim is to make this guide as thorough as possible so if you already know some of the following parts please just skip them.
If anything is missing or you find something unclear please leave a comment and I will correct it.
The outline of we are going to do is:

  • Download and install Python
  • Download and install PyQt
  • Download and install Eclipse
  • Download and install Pydev
  • Getting code completion for PyQT in Eclipse
  • Creating files and coding a tiny PyQT GUI
  • Download and install Python

    First you need python installed on your computer. I suggest you download Python 2.6.5 because it is widely supported. For Windows users, use the windows installer suitable for your system. They will suggest you install Python in c:\python26 and I have done so aswell. Usually I don’t like cluttering my c:\ with catalogs but for this I make an exception.

    After install is done it is nice to make python available in the command prompt regardless of the catalog you are using. Do this by adding “;c:\python26″ to PATH in your environment variables. You find your environment variables by right clicking on “My computer”, select properties and go to advanced settings.

    You should now be able to go to your command prompt and type python to start python. This is used when you are installing new libraries and trying out python commands.

    Download and install PyQt4


    PyQt is a set of Python bindings for Qt. It is needed to make Qt classes available in Python. For more info on PyQt check out the What is PyQt section at Riverbank Computing.
    Update – Install SIP
    As Will Stich (thanks again Will!) commented below you first need to download and install SIP to get PyQt to work . Do this by downloading SIP from the Riverbanks Computing download page. In this tutorial we will use sip-4.10.5.zip.
    Extract the contents of the zip where ever you please. I will put it in c:\sip-4.10.5 in this example.
    When that is done you can open the command prompt (run->cmd) and go to your SIP folder (c:\sip-4.10.5). Type “c:\python26\python.exe configure.py” and SIP will be configured.
    Installing PyQt is pretty straight forward. Go to the PyQt4 download page and download the windows installer for the PyQt version that corresponds to your python version you are using. In this example we use PyQt-Py2.6-gpl-4.7.3-2.exe.
    The windows installer will installer should do all the work for you so if you installed Python in C:\Python26 you should be fine by just pressing next all through the installer. When done your PyQt4 installation should be saved in C:\Python26\Lib\site-packages\PyQt4.

    Download and install Eclipse

    Eclipse installation is pretty straight forward. I chose Eclipse IDE for Java developers but I think any version works fine for our purpose. Unpack into program files or where you wherever. Heck you could probably put it on a USB stick if you want to.

    Download and install Pydev


    Pydev is a great plugin for Eclipse that allows python syntax highlighting and code completion. It can be installed in two ways; either you download and unpack the files into the plug-in folder in your Eclipse directory or you use the installation manager in Eclipse. I suggest you use the installation manager!

    So, start eclipse, choose a workspace you want to use and go to “Help -> Install new software…”. Press “Add…” and enter a name of the plugin (Pydev) and the pydev plugin update URL: http://pydev.org/updates/ (the url might change so if it doesn’t work, go to the pydev site). Follow the steps in the installation guide. You might get a bunch of dialog boxes warning you about stuff, I just pressed yes all the way and it worked fine.

    The Eclipse intallation manager, installing PyDev

    When that is done we can create our first Python project with Pydev. Your “File -> New” menu should look like the image below. Select “Pydev Project”.

    A new dialog box will open. Write the name of your project in the “Project name:” field. If this is the first time you create a Python project you will need to configure your Python interpreter. Do so by clicking on the “Click here to configure an interpreter not listed” link. A new dialog box will open that looks like the one in the image below.

    Before finding the Python interpreter

    Press the “Auto Config” box and Pydev will (hopefully) find your installed python interpreter. The auto config dialog findings should open in a new dialog that looks like the one below. Select the ones selected in the figure below and click “OK”.

    Auto finding the Python Interpreter

    Now this might be over pedagogical but your Python Interpreters box should look like the figure below. Press OK we are done with the interpreters!

    The Python Interpreters found

    Now press “Finish” to create your Pydev project. Eclipse and Pydev will create a src folder and show the referenced Python interpreter.

    Getting code completion for PyQT in Eclipse

    Not having code completion while learning something new or using a new library is a pain so lets try to avoid that! To get code completion for your PyQT library we need to add it to the external libraries included in the project. Go to the menu Project -> Properties -> PyDev PYTHONPATH -> External Libraries -> Add source folder. Add the path where you have installed your PyQT files. They are most likely, if you used the windows installer, locaded in C:\Python26\Lib\site-packages\PyQt4. If all is well you should have something that looks like the figure below.

    Setting up the PyQT in external libraries

    Creating files and coding a tiny PyQT GUI

    Now we are done with the development environment things! Lets try if this thing works! First thing we need to do is to add a main module. Do this by right clicking on your src-folder select new -> Pydev Module. In the “Name” field enter “Main”  and in the template. You could name the file anything you like, it will work either way, but it is in my opinion always nice to have a startup file called Main. It should look like the image below.

    Creating a new PyDev Project

    This will create a new main module for you with the code below

    '''
    Created on 2 apr 2010
    
    @author: Mikael Halén
    '''
    
    if __name__ == '__main__':
        pass

    Now, since this just is a small example I will put all the code in this file. If you would to start a bigger project you would probably want to create a new file for your user interface.

    Anyway, we want to create a QT GUI so lets start doing that! I’m going to describe this process by first showing you the end result and then I’m going to describe what the different rows do afterwords. Here is what we will end up with:

    The tiny PyQT GUI running in Windows

    And this is the code you need to get it working:

    from PyQt4 import QtGui
    
    class HelloPython(QtGui.QWidget):
        def __init__(self, parent=None):
            super(HelloPython, self).__init__(parent)
            helloLabel = QtGui.QLabel("Say Hello To PyQT!")
            helloLineEdit = QtGui.QLineEdit()
    
            mainLayout = QtGui.QGridLayout()
            mainLayout.addWidget(helloLabel, 0, 0)
            mainLayout.addWidget(helloLineEdit, 0, 1)
    
            self.setLayout(mainLayout)
            self.setWindowTitle("My Python App")
    
    if __name__ == '__main__':
        import sys
    
        app = QtGui.QApplication(sys.argv)
    
        helloPythonWidget = HelloPython()
        helloPythonWidget.show()
    
        sys.exit(app.exec_())
    

    Now lets see what that means. Lets start from the top!

    from PyQt4 import QtGui
    

    This imports the Qt libraries needed for this little application. We only needed the QtGui so that is what we imported.

    class HelloPython(QtGui.QWidget):
    

    This is your Main class. This line creates the class called HelloPython and says that it should inherit from QtWidget which is the base Qt class for all user interface objects.

        def __init__(self, parent=None):
            super(HelloPython, self).__init__(parent)
    

    This is the class constructor and it will be called when you instantiate the object. These two rows will make this class have no parent and thus making it the main class.

            helloLabel = QtGui.QLabel("Say Hello To PyQT!")
            helloLineEdit = QtGui.QLineEdit()
    
            mainLayout = QtGui.QGridLayout()
            mainLayout.addWidget(helloLabel, 0, 0)
            mainLayout.addWidget(helloLineEdit, 0, 1)
    
            self.setLayout(mainLayout)
            self.setWindowTitle("My Python App")
    

    These lines are QT specific. First one Label is instantiated for displaying text and then one LineEdit for entering text in. Then a GridLayout is set up where we put the Label and LineEdit. Lastly we set the layout in on the QWidget and set the window title.

    if __name__ == '__main__':
    

    This is the main python module and this line of code makes this a standalone application.

        import sys
    

    sys is a necessary import for sys.exit(app.exec_()) later in this file.

        app = QtGui.QApplication(sys.argv)
    

    A QT application must have a application object. The sys.argv are command line arguments passed on to the application.

        helloPythonWidget = HelloPython()
        helloPythonWidget.show()
    

    Instantiation of the QtWidget and displaying it for the user.

      sys.exit(app.exec_())
    

    Here we enter the main loop and all events are handled. On exit() the loop ends and sys.exit() makes sure the exit of the application is handled correctly by the system.

    Conclusion

    With this guide I hope you can easily get started programming GUI applications in Python. Again, if you find that something is unclear, missing or plain wrong please leave a comment or contact us in some other way and we will fix it. I will continue posting solutions I use for the problems I encounter while developing in QT so please subscribe to our RSS feed or follow us on twitter.
    If you want to read more visit the learning python blog or read zetcode’s python tutorials. You should also visit the PyQT class reference library at www.riverbankcomputing.co.uk.

    Updates

    5 May 2010

    There is a great set of tutorials (and a link to this post) that you can use for further learning at the diotavelli PyQTWiki


    • http://popdevelop.com Johan Brissmyr

      Really nice tutorial Mike! I’ll try this out on the train to work tomorrow

    • http://mikaelhalen.com Mikael Halén

      Thanks! I’m glad you liked it!

    • http://serijaa.top-store.de/?financegames=funbrain-arcade-game-75 houpeq

      Matchless topic, it is pleasant to me))))

    • http://popdevelop.com/2010/04/how-to-build-an-executable-application-from-your-python-script-qt-special/ How to build an executable application from your Python script (QT special) « popdevelop

      [...] do this last week so if you don’t know how to implement a GUI app using QT please follow the Setting up IDE and creating a cross platform QT Python GUI application guide. The code in script we used in that example is shown below and requires that you have [...]

    • http://vldostizhenie.patzen.de/?financegames=printable-poker-rules-31 Brage

      I will know, many thanks for the information.

    • http://popdevelop.com/2010/05/an-example-on-how-to-make-qlabel-clickable/ An example on how to make QLabel clickable « popdevelop

      [...] go ahead and download the source code. If you can’t get the code up and running, please follow our guide on how to set up your Python IDE together with QT. Lets start with the part where the problem first [...]

    • http://krusinis.t35.com avaibiliurige

      Interesting and informative. But will you write about this one more?

    • michael

      Starting from scratch, should there also be a step to download/install PyQt4. The windows PyQt binaries nicely includes Qt4 designer etc. I know this step all too well because there are still problems with the OSX 10.6 install.

    • http://mikaelhalen.com Mikael Halén

      Thanks for pointing it out Michael! I can’t imagine how I missed it. I will add a part regarding PyQt4 as soon as I get the time (probably tomorrow).

    • http://mikaelhalen.com Mikael Halén

      Post updated with PyQt4 section.

    • http://popdevelop.com/2010/07/an-example-on-how-to-use-oauth-and-python-to-connect-to-twitter/ An example on how to use Oauth and Python to connect to twitter « popdevelop

      [...] in this post. If you never built an application using Python before, check out our guide to GUI programming using Python. Lets get [...]

    • James Moon

      Hello.

      I followed the tutorial, but Eclipse cannot import QtGui..

      Error ; Unresolved import : QtGui..

      Would you help me to start?..

    • James Moon

      Sorry.. I re installed all programs.. Works fine.

      Python 3.1.2
      PyQt-Py3.1-gpl-4.7.4-1
      Eclipse Java

      19th July 2010.

      Thanks. Great help.
      I will post what I do next month.

    • http://mikaelhalen.com Mikael Halén

      I was just about to check what might have gone wrong when I got the new comment. Great that it worked out for you and that it works with Python 3 as well! I’m looking forward to reading your post!

    • Will Sitch

      I’m also having problems with Python 2.6: Error ; Unresolved import : QtGui..

      Will

    • http://mikaelhalen.com Mikael Halén

      After reviewing the post I think I might have missed some step where PyQt is installed. It might be that the PyQt installer doesn’t add the PyQt4 path to your environment variables but I’m not sure. I will have a look at it when I as soon as I get some free time. While you’re waiting, try adding “C:\Python26\Lib\site-packages\PyQt4″ (or where PyQt is installed) to your environment variables.

      If you find out what was wrong, it would be great if you posted the solution here so that I can complete the tutorial without an unnecessary investigation.

      Thanks!

    • Will Sitch

      Ok, got it to work. You need to install SIP before installing PyQt4.

      SIP is available from here:
      http://www.riverbankcomputing.com/software/sip/download

      Download, unzip to the root directory, run a program “cmd” to open a DOS-like command window, change to the directory, and run the configure program with your previously-installed Python executable. For me, this was:
      cd \sip-4.10.5
      c:\python26\python.exe configure.py

      Once installed, you need to make sure the PYTHONPATH external library reference points to C:\Python26\Lib\site-packages\PyQt4, not C:\Python26\Lib\site-packages\PyQt4\sip\PyQt4 as is recommended above.

      After those changes I was able to make it work. Good luck everyone.

      Will

    • http://mikaelhalen.com Mikael Halén

      Ah! I forgot about SIP. Thanks for writing how you solved the problem. The PYTHONPATH you wrote is the correct one, I don’t know where I got the other one from. I will update the post according to what you suggested.
      Thanks again Will!

    • James Moon

      Hello.. Mikael.

      Another question..

      I want to use QT designer.. Of course..!! ^^

      What is better and more convenient way to use
      a) just QT Designer b) QT Designer integrated for Eclipse

      I hope you make another tutorial for using QT Designer with PyQT..

      Your help increas my working speed.

      Regards.

    • http://mikaelhalen.com Mikael Halén

      Hi James,

      to tell you the truth I never tried the Qt designer but I am eager to try it out! It would be a real time saver and a step in the right direction to do so. Hand coding GUIs can be a mess!

      If I try out the Qt designer in eclipse I will write a post on how to get it up and running.

      Thanks for the comment!

    • http://mikaelhalen.com Mikael Halén

      Post updated. Sorry about the delay, vacation times :]

      Thanks again for the solution!

    • Helmut Tauscher

      I get the following error message. I did the installation exactly as described above. What is wrong?

      Traceback (most recent call last):
      File “D:\Data\Workspace\Python\src\Main.py”, line 7, in
      from PyQt4 import QtGui
      ImportError: DLL load failed: Das angegebene Modul wurde nicht gefunden.

      Thanks

      Helmut

    • http://mikaelhalen.com Mikael Halén

      Hi Helmut,

      it is hard to tell exactly what might have gone wrong. I would probably have checked that PyQt is installed as it should. If you open python in the command prompt (c:\python26\python.exe) and try writing “from PyQt4 import QtGui” and get the same message PyQt probably isn’t installed as it should.
      Could you verify that there are a bunch of PyQt DLLs located in “c:\python26\lib\site-packages\pyqt4″? If it is located there and it still doesn’t work my best guess is to re-install SIP and then PyQt again.

      There is a stackoverflow question similar to this one, it might help: http://stackoverflow.com/questions/2140836/pyqt-4-7-importerror-after-installing-on-windows

      I hope this helps you to fix it, please come back if the problem still is there.

    • Helmut Tauscher

      Mikael,

      if I try exact the same code within IDLE everything works fine. But I want to use Eclipse as my IDE.
      I verified PyQt DLLs. There are no DLL in this folder. I will reinstall everything and try again.

      thanks.

    • Zach Jacobs

      @james – I’ve used QT designer in the past and it’s fairly straightforward to use. Just design your GUI, save it as a .ui file and convert to .py file using the ‘pyuic4′ command on the command line to create a .py file out of it.

      1. pyuic4 gui.ui > gui.py
      2. add gui.py to your eclipse project

      This might help a bit: “http://www.rkblog.rk.edu.pl/w/p/introduction-pyqt4/”

      It’s easiest to have gui.ui and gui.py in your workspace directory as eclipse will just reload gui.py if you change the gui and have to re-run the command. Be very careful to not customize your gui.py file inside Eclipse as it will be overwritten whenever you change the gui and run the pyuic4 command.

      This method is easy, but it’s kind of annoying to go back to the command line every time you want to change the UI.

      Hope that helps and I would love to see an explanation of how to integrate QT designer into Eclipse!

    • http://mikaelhalen.com Mikael Halén

      Hi Zach,

      thanks for the reply!

    • http://www.tamerz.com/?p=22 Tamerz.com » Python, PyQt, and PyDev for Eclipse

      [...] http://popdevelop.com/2010/04/setting-up-ide-and-creating-a-cross-platform-qt-python-gui-application... Tamerz September 24, 2010 Development Facebookfacebook TwitterTwitter stumbleuponstumbleupon del.icio.usdel.icio.us Buzz [...]

    • Janne Roivainen

      Thank You Mikael!

      I managed to install everything correct and the thing works…strange…:-) What I started to wonder is that have you tried/do you know anyone who has…to include the PyQwt as well? I could use the scientific stuff (widgets) in my projects…Once again…Thanks! You Made My Day!

    • http://mikaelhalen.com Mikael Halén

      Hi Janne,

      I’m super happy to hear that this guide still works and that it helped you to get it up and running! It amazes me every time! :]
      I haven’t gotten the time to try out PyQwt but it does look useful. Might have a look at it sometime.

      Keep up the good work with creating PyQt applications!

      Mike

    • http://rightbrainedpython.wordpress.com/2010/12/27/hello-python/ Hello PYTHON « Python- The Right Brained way

      [...] might enjoy it a lot. See this page as how to install PYdev on Eclipse, and even make it Qt ready.http://popdevelop.com/2010/04/setting-up-ide-and-creating-a-cross-platform-qt-python-gui-application... Comments RSS feed LikeBe the first to like this [...]

    • http://softwarefindings.wordpress.com Rohit

      Very good article. I desperately needed.

      I am using Aptana Studio 3 Beta with PyDev plugin. I installed all the other things as you suggested and configured the settings as you suggested, still I am not able to Run my program. It is generating error:

      Traceback (most recent call last):
      File “G:\Users\RP\My Documents\Aptana Studio 3 Workspace\FirstGui1\src\Main\testGui.py”, line 1, in
      from PyQt4 import QtGui
      ImportError: DLL load failed: The specified module could not be found.

    • Leviathan

      Nice work Mikael!
      I was hoping for someone to set up just exactly a tutorial like this!
      I had some problems at first, because I didn’t install SIP at first, but after I reinstalled it (and Qt… and I might have tweaked some parameters…) it worked fine.

      Thanks a lot for the detailed article.

      By the way, I’m using (or planning to use) Python3.1.

    • Etha

      Great post! thanks!

    • http://e-tut.de/2011/linux-ide-fuer-pyqt-einrichten/ Linux: IDE für PyQt einrichten « e-TuT.de – Weblog

      [...] Python3, Qt4, PyQt4 und Eclipse installieren. Danach müsst ihr einige Schritte folgen, welche ihr hier findet. Anschließend installiert ihr QT für Ecplise und dann kann es auch schon [...]

    • Ian

      Brilliant. The first straight-forward tutorial on this subject that I have read so far.  It worked first time.

    • http://iizukak.com/?p=992 Python + Eclipse + PyDev + PyQtでサクサクGUI開発できる環境をつくる | iizukak blog

      [...] ・Eclipse ・popdevelop カテゴリー: Python   パーマリンク ← [...]

    • kon

      Thanks!

      The most complete tutorial i stumbled upon until now!

    • Saibabu3639

      I am raj if u dont mine can anyone tell me how to run this python program with monkey runner so can anyone suggest me the procedure to run this example 

    • Anders Holmström

      Thanks for a great tutorial on setting this combo up. I’m happy to inform you that as of 2012-02-09 this still works without a hitch – even with PySide instead of PyQt.

    • http://www.globalgenericpharmacy.com/viagra.html Generic Viagra

      This JavaFX tutorial describes how to develop graphical user interfaces (GUIs) including visual effects and animation for web applications and Java applets.

    • HelloWorld User

      Thank you very much !!

    • Qingnian2

      i download pyside . didn’t find the source forlder

    • Byhanjo

      It would be nice if there was any way to connect Eclipse with QT Designer for creatingforms.

    • CV

      For Linux (Debian), the path of PyQt is /usr/bin. It works fine. Thanks.

    • http://www.DeckardSays.es/pyqt-en-windows/ PyQT en Windows | Deckard Says

      [...] aquello necesario para empezar con PyQT. El tutorial que se muestra aquí es una traducción de este tutorial escrito por Mikael Halén actualizado a mayo de [...]

    • Muhammad Bashir Al-Noimi

       Recently, this way doesn’t work with me… could you please take a look to my problem here
      http://stackoverflow.com/questions/10499114/unable-to-parse-pyqt-files-and-code-completion-doesnt-work

    • Nikunj Vadher

      superbbb….
      exact and point to point guidance..
      thanks a lot..

    • http://www.register-web-domain.in/ Domain Registration India

      Step By Step Very Clear Information ..Thanks 

    • Marc

      Really good tutorial. Thanks a lot :)

    • Andrea Vartanian

      I’m persian ( from iran ), i can’t understand english well, and i would find a usable document for starting python for windows, but i waste 3 months of my life and i couldn’t find anything usable, but this is awesome!

      for me, with foreign language, your note was really awesome!
      thank you man, you’re fantastic…

    • Andrea Vartanian

      everything works fine!!! again, thanks Mikael…

    • http://www.yepi250.com/ yepi250

      I like to show my appreciation for great writing. You should know your article is very informative as well as persuasive. This shows your talent.

    • Ardis

      Awesome thank you!