Питон как сделать всплывающее окно pyqt

от admin

Python PyQt5: современные графические интерфейсы для Windows, MacOS и Linux

Python регулярно включают в разнообразные рейтинги лучших языков программирования благодаря большому сообществу и легко читаемому синтаксису. Более того, Python под силу создать современный графический пользовательский интерфейс — GUI — для обычных скриптов. В руководстве уделим внимание модулю для разработки GUI PyQt5 , но стоит также упомянуть аналоги: Tkinter и WxWidget .

Статья подойдет в том числе и начинающим программистам, поэтому, не теряя времени, приступаем!

Содержание руководства:

  1. Установка и настройка PyQt5.
  2. Основы PyQt5.
  3. Заголовок окна.
  4. События и кнопки.
  5. Поля ввода.
  6. Окна сообщений и всплывающие окна.
  7. Выводы.

1. Установка и настройка PyQt5

Скачайте и установите последнюю версию Python для вашей системы, а если Python уже на месте, то установите пакеты при помощи следующей команды (откройте командную строку, введите и нажмите Enter):

2. Основы PyQt5

Теперь на вашем компьютере сохранен пакет PyQt5 , поэтому давайте начнем с написания первого окна графического интерфейса. Откройте ваш любимый текстовый редактор или IDE и выполните приведенный ниже код:

Результат выполнения программы:

Теперь разберем код окна интерфейса с заголовком сверху. Если обсуждать кратко, то в первую очередь импортируем PyQt5 и его классы, полезные в создании виджета GUI, а затем создаем функцию main() для реализации оконного интерфейса.

  • QMainWindow() — словно контейнер, содержащий все виджеты, такие как кнопки, текст, поле ввода и т. д.
  • SetGeometry() — один из методов QMainWindow() , устанавливает размер окна. Синтаксис: setGeometry(x, y, длина, ширина) .
  • SetWindowTitle() — устанавливает заголовок окна.
  • Win.show() — создает и отображает весь разработанный интерфейс.
  • Sys.exit(app.exec_()) — устанавливает, что конкретное окно не закроется без нажатия на кнопку с крестиком. Без этой строчки кода GUI-программа завершится через секунду после выполнения.

3. Заголовок окна

Label Text — это текст, отображаемый внутри окна. С написанием Label Text в PyQt5 вам поможет виджет Qlabel .

Выполните следующий код:

Результат выполнения программы:

Если кратко, то вызываем метод Qlabel() и передаем в него переменную QMainWindow .

  • Метод SetText() устанавливает Label Text, в качестве аргумента принимает только строковые данные.
  • Метод Move(x, y) применяется для установки положения Label Text внутри окна.

4. События и кнопки

Кнопки — важная часть любого программного обеспечения, ведь именно кнопка определяет действие пользователя, а следовательно, и результат работы программы тоже. Для создания кнопок в PyQt5 придётся применить другой виджет под названием QtWidgets , выполните следующий код:

Результат выполнения программы:

В коде вышеизложенного примера переменная QMainWindow передается в метод из Qwidget под названием QPushbutton . Далее разберем код примера по пунктам.

  • SetText() устанавливает название для кнопки, как можно увидеть на приведенном выше изображении.
  • Move() снова применяется для установки положения кнопки в окне по координатам на осях x и y.

Теперь пришел черед событийно-ориентированного программирования (Event-Driven-Programming)! Проще говоря, нужно определить действие для кнопки, то есть, если пользователь на нее нажмет, то что-то должно произойти. Ознакомьтесь со следующим кодом, а дальше рассмотрим подробные объяснения:

Теперь в примере определяется не только главная функция по имени main() , но и функция по имени click() , передающаяся в качестве параметра для button.clicked.connect() в main() . Таким образом указывается конкретная функция, срабатывающая при нажатии на конкретную кнопку.

Запустив такой код и нажав на кнопку, вы увидите вывод на экране консоли. Дело за вами, что же написать внутри функции click() ! Протестируйте код на вашей операционной системе.

5. Поля ввода

Поля ввода также называются текстовыми полями — это области для пользовательского ввода информации. Для объявления поля ввода в PyQt5 применяется специальный виджет QlineEdit() , а в него, как обычно, передается в качестве параметра QMainWindow .

Посмотрите на следующий код и обратите внимание на его результат:

Результат выполнения программы:

  • Resize(width, height) изменяет размер виджета поля ввода.

6. Окна сообщений и всплывающие окна

Окна сообщений и всплывающие окна (popups) — это альтернативные маленькие окна, например, вы создаете программу для регистрации электронной почты, а пользователь не ввел надежный пароль, тогда вы предупреждаете пользователя об этом через окна сообщений.

Для создания окон сообщений в PyQt5 применяется виджет QMessageBox , он опять таки принимает QMainWindow в качестве параметра.

Проанализируйте следующий код:

Результат выполнения программы:

  • SetWindowTitle() устанавливает заголовок для окна сообщения.

Также в окне сообщения всегда можно показать специальный значок, как показано в следующем коде и результате его выполнения:

Результат выполнения программы:

Ниже приведен список допустимых для окон сообщений значков:

  • QMessageBox.Warning
  • QMessageBox.Critical
  • QMessageBox.Information
  • QMessageBox.Question

Выводы

Что же, руководство предоставило вам все необходимые знания для самостоятельного создания графических пользовательских интерфейсов на PyQt5 .

PyQt5 Dialogs and Alerts
Notify your users and ask for their input

Dialogs are useful GUI components that allow you to communicate with the user (hence the name dialog). They are commonly used for file Open/Save, settings, preferences, or for functions that do not fit into the main UI of the application. They are small modal (or blocking) windows that sit in front of the main application until they are dismissed. Qt provides a number of ‘special’ built-in dialogs for the most common use-cases, allowing you to provide a platform-native user experience.

Standard GUI features — A search dialogStandard GUI features — A search dialog

Standard GUI features — A file Open dialogStandard GUI features — A file Open dialog

In Qt dialog boxes are handled by the QDialog class. To create a new dialog box simply create a new object of QDialog type passing in another widget, e.g. QMainWindow , as its parent.

Let’s create our own QDialog . We’ll start with a simple skeleton app with a button to press hooked up to a slot method.

In the slot button_clicked (which receives the signal from the button press) we create the dialog instance, passing our QMainWindow instance as a parent. This will make the dialog a modal window of QMainWindow . This means the dialog will completely block interaction with the parent window.

Run it! Click the button and you’ll see an empty dialog appear.

Once we have created the dialog, we start it using .exec() — just like we did for QApplication to create the main event loop of our application. That’s not a coincidence: when you exec the QDialog an entirely new event loop — specific for the dialog — is created.

The QDialog completely blocks your application execution. Don’t start a dialog and expect anything else to happen anywhere else in your app. We’ll see later how you can use threads & processes to get you out of this pickle.

Our empty dialog overlaying the window.Our empty dialog overlaying the window.

Like our very first window, this isn’t very interesting. Let’s fix that by adding a dialog title and a set of OK and Cancel buttons to allow the user to accept or reject the modal.

To customize the QDialog we can subclass it.

In the above code, we first create our subclass of QDialog which we’ve called CustomDialog . As for the QMainWindow we apply our customizations in the class __init__ block so our customizations are applied as the object is created. First we set a title for the QDialog using .setWindowTitle() , exactly the same as we did for our main window.

The next block of code is concerned with creating and displaying the dialog buttons. This is probably a bit more involved than you were expecting. However, this is due to Qt’s flexibility in handling dialog button positioning on different platforms.

You could of course choose to ignore this and use a standard QButton in a layout, but the approach outlined here ensures that your dialog respects the host desktop standards (OK on left vs. right for example). Messing around with these behaviors can be incredibly annoying to your users, so I wouldn’t recommend it.

Читать:
Как изменить порядок загрузки операционных систем linux windows в grub

The first step in creating a dialog button box is to define the buttons want to show, using namespace attributes from QDialogButtonBox . The full list of buttons available is below.

  • QDialogButtonBox.Ok
  • QDialogButtonBox.Open
  • QDialogButtonBox.Save
  • QDialogButtonBox.Cancel
  • QDialogButtonBox.Close
  • QDialogButtonBox.Discard
  • QDialogButtonBox.Apply
  • QDialogButtonBox.Reset
  • QDialogButtonBox.RestoreDefaults
  • QDialogButtonBox.Help
  • QDialogButtonBox.SaveAll
  • QDialogButtonBox.Yes
  • QDialogButtonBox.YesToAll
  • QDialogButtonBox.No
  • QDialogButtonBox.Abort
  • QDialogButtonBox.Retry
  • QDialogButtonBox.Ignore
  • QDialogButtonBox.NoButton

These should be sufficient to create any dialog box you can think of. You can construct a line of multiple buttons by OR-ing them together using a pipe ( | ). Qt will handle the order automatically, according to platform standards. For example, to show an OK and a Cancel button we used:

The variable buttons now contains an integer value representing those two buttons. Next, we must create the QDialogButtonBox instance to hold the buttons. The flag for the buttons to display is passed in as the first parameter.

To make the buttons have any effect, you must connect the correct QDialogButtonBox signals to the slots on the dialog. In our case we’ve connected the .accepted and .rejected signals from the QDialogButtonBox to the handlers for .accept() and .reject() on our subclass of QDialog .

Lastly, to make the QDialogButtonBox appear in our dialog box we must add it to the dialog layout. So, as for the main window we create a layout, and add our QDialogButtonBox to it ( QDialogButtonBox is a widget), and then set that layout on our dialog.

Finally, we launch the CustomDialog in our MainWindow.button_clicked slot.

Run it! Click to launch the dialog and you will see a dialog box with buttons.

Our dialog with a label and buttons.Our dialog with a label and buttons.

When you click the button to launch the dialog, you may notice that it appears away from the parent window — probably in the center of the screen. Normally you want dialogs to appear over their launching window to make them easier for users to find. To do this we need to give Qt a parent for the dialog. If we pass our main window as the parent, Qt will position the new dialog so that the center of the dialog aligns with the center of the window.

We can modify our CustomDialog class to accept a parent parameter.

We set a default value of parent=None so we can omit the parent if we wish.

Then, when we create our instance of CustomDialog we can pass the main window in as a parameter. In our button_clicked method, self is our main window object.

Run it! Click to launch the dialog and you should see the dialog pop up right in the middle of the parent window.

Our dialog, centered over the parent window.Our dialog, centered over the parent window.

Congratulations! You’ve created your first dialog box. Of course, you can continue to add any other content to the dialog box that you like. Simply insert it into the layout as normal.

Simple message dialogs with QMessageBox

There are many dialogs which follow the simple pattern we just saw — a message with buttons with which you can accept or cancel the dialog. While you can construct these dialogs yourself, Qt also provides a built-in message dialog class called QMessageBox . This can be used to create information, warning, about or question dialogs.

The example below creates a simple QMessageBox and shows it.

Run it! You’ll see a simple dialog with an OK button.

A QMessageBox dialog.A QMessageBox dialog.

As with the dialog button box we looked at already, the buttons shown on a QMessageBox are also configured with the same set of constants which can be combined with | (the binary OR operator) to show multiple buttons. The full list of available button types is shown below.

  • QMessageBox.Ok
  • QMessageBox.Open
  • QMessageBox.Save
  • QMessageBox.Cancel
  • QMessageBox.Close
  • QMessageBox.Discard
  • QMessageBox.Apply
  • QMessageBox.Reset
  • QMessageBox.RestoreDefaults
  • QMessageBox.Help
  • QMessageBox.SaveAll
  • QMessageBox.Yes
  • QMessageBox.YesToAll
  • QMessageBox.No
  • QMessageBox.NoToAll
  • QMessageBox.Abort
  • QMessageBox.Retry
  • QMessageBox.Ignore
  • QMessageBox.NoButton

You can also tweak the icon shown on the dialog by setting the icon with one of the following.

Icon state Description
QMessageBox.NoIcon The message box does not have an icon.
QMessageBox.Question The message is asking a question.
QMessageBox.Information The message is informational only.
QMessageBox.Warning The message is warning.
QMessageBox.Critical The message indicates a critical problem.

For example, the following creates a question dialog with Yes and No buttons.

Run it! You’ll see a question dialog with Yes and No buttons.

Question dialog created using QMessageBox.Question dialog created using QMessageBox.

PyQt QMessageBox

Summary: in this tutorial, you’ll learn how to use the PyQt QMessageBox class to create a modal dialog that alerts the user or asks the user to make a decision.

Introduction to PyQt QMessageBox class

The QMessageBox class allows you to create a modal dialog that alerts the user with important information or asks the user a question and receives an answer.

The QMessageBox provides some useful static methods for displaying a message box:

  • information() – show an information message.
  • question() – ask the user a question and receives an answer.
  • warning() – show a warning message.
  • critical() – display critical information.

PyQt QMessageBox examples

The following program shows a window with four buttons, clicking a button will display a corresponding message:

The question() method displays a message box with a question that asks the user to select either a Yes or No button:

To get which button the user clicked, you compare the return value of the question() method with the Yes and No members of the QMessageBox.StandardButton enum:

The information() method displays a message box with information. It accepts the parent widget, the title of the message box, and the message.

PyQt-QMessageBox-Information-Message

The warning() method displays a warning message. Its appearance is like the information except for the warning icon:

The critical() method displays a critical message on the message box. The stop icon makes the message critical.

Python: PyQt Popup Window

So I’ve been creating my GUI with Qt for my Python application. I’ve now come to a situation where after a button has been pushed the appropriate deferred gets executed, we perform some tasks then I need to open up a separate window that contains one or two things. But I can’t seem to figure out how to create this new separate window. Could anyone give me an example of how to create one?

2 Answers 2

A common error that can drive you crazy is forgetting to store the handle of the popup window you create in some python variable that will remain alive (e.g. in a data member of the main window).

The following is a simple program that creates a main window with a button where pressing the button opens a popup

What I think can be surprising for Python users and may be is the problem you are facing is the fact that if you don’t store a reference to the new widget in the main e.g. by using w = MyPopup(. ) instead of self.w = MyPopup(. ) the window apparently doesn’t appear (actually it’s created and it’s immediately destroyed).

The reason is that when the local variable w goes out of scope as no one is explicitly referencing the widget the widget gets deleted. This can be seen clearly because if you press again the button you’ll see that as the second popup appears the first one is closed.

Related Posts