Install pyqt on windows

Install pyqt

PyQt is often not installed by default. The PyQt module can be used to create desktop applications with Python. In this article you’ll learn how to install the PyQt module.

Desktop applications made with PyQt are cross platform, they will work on Microsoft Windows, Apple Mac OS X and Linux computers (including Raspberry Pi).

How to install PyQt5 on Windows?

To install PyQt on Windows there are a few steps you need to take.
First use the installer from the qt-project website, from qt to install PyQt.

Next you want to install a Python version 3.3 or newer. Check the box to add all of the PyQt5 extras. It’s not necessary to compile everything from source, you can install all the required packages with the installer.

On Python >= 3.6, you can also try this command:

It should work without problems.

How to install PyQt5 on Mac OS X?

On Apple Mac OS X installation is a bit simpler. The first step to take is to install the Mac OS X binary. This installs the PyQt GUI library.

But to use it from Python, you also need Python module. This is where the tool brew comes in.
You can use brew to install pyqt (in the terminal):

How to install PyQt5 on Linux?

Python is often installed by default on Linux (in nearly all of the distributions including Ubuntu). But you want to make sure to use Python 3, because of all the features and ease of use. You can verify that you have the newest Python version with the command:

On Ubuntu Linux they sometimes include two versions of python, python3 and python . In that case use Python 3.

Once you have Python ready, the next step is to install PyQt.

This isn’t hard to do if you have some Linux experience. You can install PyQt your software package manager. Which package manager to use depends on which Linux distribution you are using.

On Ubuntu Linux / Debian Linux you can use the command:

Install pyqt on windows

У становка Python и PyQT под Windows

Я решил выучить Python потому что он довольно прост. Мало того, с помощью PyQT можно делать кроссплатформенные приложения, одинаково хорошо работающие на Windows и Linux.Я прекрасно знал, что в Python комфортнее работать из под Linux, но ради обучения устанавливать другую ОС не хотелось, поэтому я решил установить Python в Windows. Качаем последнюю версию Python с официального сайта https://www.python.org/downloads/windows/0 Последней версией оказалась 3.6. На первом экране установки обязательно поставьте галочку «Добавить в PATH»

Теперь нам нужно поставить PyQT — библиотеку для создания на Python оконных приложений.Для этого ее придется поставить дважды, один раз через pip а второй раз с помощью установщика под Windows.

Двойная установка нужна для того чтобы у нас было налажено взаимодействие с последней версией Python, а в меню Пуск была программа Designer.

Читайте также:  Open ports windows command

Сперва в командной строке Windows даём команду

pip install pyqt5

и ждём когда скачается и установится PyQT5.

После этого качаем и устанавливаем .exe установочный файл отсюда:

Если вы используете более менее свежую версию Python и PyQT будьте готовы, что примеры из книг 2012-14 года выпуска могут банально не совместимы с вашим софтом.

Вместе с PyQT ставится куча полезных примеров — папку с ними можно найти в меню Пуск.Эти примеры можно открывать через встроенный в Python редактор IDLE и запускать клавишей F5.В примерах присутствует работа с мультимедиа, камерой, richedit, и еще много интересных вещей.

Если у вас есть Android телефон, вы можете скачать наш учебник по Python

Собираем проект на python3&PyQT5 под Windows, используя PyInstaller

Причиной написания статьи, явилось огромное количество постоянно возникающих у новичков вопросов такого содержания: «Как собрать проект c pyqt5», «Почему не работает», «Какой инструмент выбрать» и т.д. Сегодня научимся собирать проекты без мучений и танцев с бубном.

Как-то пришлось написать небольшое desktop-приложение. В качестве языка программирования для разработки был выбран python, поскольку для решения моей задачи он подходил идеально. В стандартную библиотеку Python уже входит библиотека tkinter, позволяющая создавать GUI. Но проблема tkinter в том, что данной библиотеке посвящено мало внимания, и найти в интернете курс, книгу или FAQ по ней довольно-таки сложно. Поэтому было решено использовать более мощную, современную и функциональную библиотеку Qt, которая имеет привязки к языку программирования python в виде библиотеки PyQT5. Более подробно про PyQT можете почитать здесь. В качестве примера я буду использовать код:

Если вы более-менее опытный разработчик, то понимаете, что без интерпретатора код на python не запустить. А хотелось бы дать возможность каждому пользователю использовать программу. Вот здесь к нам на помощь и приходят специальные библиотеки позволяющие собирать проекты в .exe, которые можно потом без проблем запустить, как обычное приложение.

Существует большое количество библиотек, позволяющих это сделать, среди которых самые популярные: cx_Freeze, py2exe, nuitka, PyInstaller и др. Про каждую написано довольно много. Но надо сказать, что многие из этих решений позволяют запускать код только на компьютере, с предустановленным интерпретатором и pyqt5. Не думаю, что пользователь будет заморачиваться и ставить себе дополнительные пакеты и программы. Надеюсь, вы понимаете, что запуск программы на dev-среде и у пользователя это не одно и тоже. Также нужно отметить, что у каждого решения были свои проблемы: один не запускался, другой собирал то, что не смог потом запустить, третий вообще отказывался что-либо делать.

После долгих танцев с бубном и активным гуглением, мне все же удалось собрать проект с помощью pyinstaller, в полностью работоспособное приложение.

Немного о Pyinstaller

Pyinstaller собирает python-приложение и все зависимости в один пакет. Пользователь может запускать приложение без установки интерпретатора python или каких-либо модулей. Pyinstaller поддерживает python 2.7 и python 3.3+ и такие библиотеки как: numpy, PyQt, Django, wxPython и другие.

Pyinstaller тестировался на Windows, Mac OS X и Linux. Как бы там ни было, это не кросс-платформенный компилятор: чтобы сделать приложение под Windows, делай это на Windows; Чтобы сделать приложение под Linux, делай это на Linux и т.д.

PyInstaller успешно используется с AIX, Solaris и FreeBSD, но тестирование не проводилось.

Подробнее о PyInstaller можно почитать здесь: документация.

Читайте также:  Отмена тем рабочего стола windows

К тому же после сборки приложение весило всего около 15 мб. Это к слову и является преимуществом pyinstaller, поскольку он не собирает все подряд, а только необходимое. Аналогичные же библиотеки выдавали результат за 200-300 мб.

Приступаем к сборке

Прежде чем приступить к сборке мы должны установить необходимые библиотеки, а именно pywin32 и собственно pyinstaller:

Чтобы убедится, что все нормально установилось, вводим команду:

должна высветиться версия pyinstaller. Если все правильно установилось, идем дальше.

В папке с проектом запускаем cmd и набираем:

Собственно это и есть простейшая команда, которая соберет наш проект.
Синтаксис команды pyinstaller таков:

pyinstaller [options] script [script . ] | specfile

Наиболее часто используемые опции:

—onefile — сборка в один файл, т.е. файлы .dll не пишутся.
—windowed -при запуске приложения, будет появляться консоль.
—noconsole — при запуске приложения, консоль появляться не будет.
—icon=app.ico — добавляем иконку в окно.
—paths — возможность вручную прописать путь к необходимым файлам, если pyinstaller
не может их найти(например: —paths D:\python35\Lib\site-packages\PyQt5\Qt\bin)

PyInstaller анализирует файл myscript.py и делает следующее:

  1. Пишет файл myscript.spec в той же папке, где находится скрипт.
  2. Создает папку build в той же папке, где находится скрипт.
  3. Записывает некоторые логи и рабочие файлы в папку build.
  4. Создает папку dist в той же папке, где находится скрипт.
  5. Пишет исполняемый файл в папку dist.

В итоге наша команда будет выглядеть так:

После работы программы вы найдете две папки: dist и build. Собственно в папке dist и находится наше приложение. Впоследствии папку build можно спокойно удалить, она не влияет на работоспособность приложения.

Спасибо за внимание. Надеюсь статья была вам полезна.

How to install PyQt5 on Windows?

When I try installing the PyQt5 on Windows using the command

I get this error:

I got the pyQt5 from PyQt5 Download.

How can I install PyQt5?

Update:

I installed Qt 5.0.2 for Windows 64-bit (VS 2012, 500 MB) from the Qt Download page and now I have this error:

And when I execute the command python configure.py —verbose :

I added C:\Program Files (x86)\Microsoft Visual Studio 11.0\VC\bin (contains nmake.exe ) to PATH and I got this error:

16 Answers 16

The easiest way to install PyQt is to just use the installer (Link in your answer, step #5). If you install python 3.3, the installer will add all of the PyQt5 extras to that python installation automatically. You won’t need to do any compiling (none of: nmake, nmake install, python configure).

All of the build options are available for if you need a custom install (for instance, using a different version of python, where there isn’t an installer provided by riverbank computing).

If you do need to compile your own version of PyQt5, the steps (as you have found) are here, but assume you have python and a compiler installed and in your path. The installed and in your path have been where you have been running into trouble it seems. I’d recommend using the installer version, but you need to install python 3.3 first.

Mainly I use the following command under the cmd

And it works with no problem!

First try this in your Windows cmd window:

If that is successful, it will look something like this:

If that did not work, you might try this link from SourceForge.

How to find the installer that’s right for you?

Читайте также:  Initramfs linux не загружается debian

First, determine what version of Python you have and whether you have 32-bit or 64-bit Python. Next, open one of the directories. I’m on Python 3.5 64-bit so I’m looking for a .exe with those specs. When you open a directory on SourceForge, you will see some directories with ONLY .zip or .tar.gz. That’s not what you’re looking for. A good indication of which directory you should click is given by the «Downloads/Week» column. I’ll open the PyQt-5.6 directory in my case.

Here we notice some .exe files:

I know these are Python 3.5 by Py3.5 in the file name. I am also looking for the 64-bit version so I’ll download PyQt5-5.6-gpl-Py3.5-Qt5.6.0-x64-2.exe . Final answer!

Note: if you try to install a version that’s not compatible with your system, a dialog box will appear immediately after running the .exe. That’s an indication that you’ve chosen the wrong one. I’m not trying to sound like a dbag. I did that several times!

To test a successful install, in your Python interpreter, try to import:

How to install PyQt4 on Windows using pip?

I’m using Python 3.4 on Windows. When I run a script, it complains

So I tried to install it, but pip install PyQt4 gives

Could not find any downloads that satisfy the requirement PyQt4

although it does show up when I run pip search PyQt4 . I tried to pip install python-qt , which installed successfully but that didn’t solve the problem.

What am I doing wrong?

13 Answers 13

Here are Windows wheel packages built by Chris Golke — Python Windows Binary packages — PyQt

In the filenames cp27 means C-python version 2.7, cp35 means python 3.5, etc.

Since Qt is a more complicated system with a compiled C++ codebase underlying the python interface it provides you, it can be more complex to build than just a pure python code package, which means it can be hard to install it from source.

Make sure you grab the correct Windows wheel file (python version, 32/64 bit), and then use pip to install it — e.g:

Should properly install if you are running an x64 build of Python 3.5.

QT no longer supports PyQt4, but you can install PyQt5 with pip:

You can’t use pip. You have to download from the Riverbank website and run the installer for your version of python. If there is no install for your version, you will have to install Python for one of the available installers, or build from source (which is rather involved). Other answers and comments have the links.

If you install PyQt4 on Windows, files wind up here by default:

but it also leaves a file here:

If you copy the both the sip.pyd and PyQt4 folder into your virtualenv things will work fine.

Then with windows explorer copy from C:\Python27\Lib\site-packages the file (sip.pyd) and folder (PyQt4) mentioned above to C:\code\BACKUP\Lib\site-packages\

Then back at CLI:

The problem with trying to launch a script which calls PyQt4 from within virtualenv is that the virtualenv does not have PyQt4 installed and it doesn’t know how to reference the default installation described above. But follow these steps to copy PyQt4 into your virtualenv and things should work great.

Оцените статью