Python > Advanced Topics and Specializations > Specific Applications (Overview) > GUI Development (Tkinter, PyQt, Kivy)
PyQt5 Simple Window
This snippet demonstrates creating a simple window using PyQt5. It shows the basic structure of a PyQt application, including creating a QApplication, a QWidget, and displaying the window.
Complete Code
This code creates a simple PyQt5 window. QApplication is the main application object. QWidget is the base class for all UI elements. setGeometry sets the window's position and size. setWindowTitle sets the title bar text. show displays the window. app.exec_() starts the event loop, and sys.exit ensures a clean exit.
import sys
from PyQt5.QtWidgets import QApplication, QWidget
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setGeometry(300, 300, 300, 220)
self.setWindowTitle('Simple PyQt Window')
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
Concepts Behind the Snippet
The snippet demonstrates the following key PyQt concepts:QApplication manages the GUI application's control flow and settings.app.exec_() function starts the event loop, which handles user interactions (e.g., mouse clicks, keyboard presses).
Real-Life Use Case
This snippet is the foundation for any PyQt application. It can be expanded to create:
Best Practices
When to Use PyQt
PyQt is suitable for:
Alternatives
Alternatives to PyQt include Tkinter, Kivy, and wxPython. Tkinter is simpler and comes standard with Python, but lacks the advanced features of PyQt. Kivy is designed for multi-touch applications. wxPython aims for a native look and feel on each platform.
Pros
Cons
FAQ
-
How do I add a button to the window?
You can add a button usingQPushButton. For example:button = QPushButton('Click Me', self); button.move(50, 50). You can then connect the button'sclickedsignal to a slot function. -
How do I change the window's background color?
You can change the background color using stylesheets. For example:self.setStyleSheet("background-color: lightblue;").