This tutorial provides a quick start to building basic windows with PyQt5, a powerful Python binding for the Qt framework. We’ll cover creating a window, resizing it, and adding an icon.
Table of Contents
Creating a Basic Window
Let’s begin by constructing the simplest PyQt5 window. This involves importing necessary modules and creating an application and a main window instance.
import sys
from PyQt5.QtWidgets import QApplication, QWidget
if __name__ == '__main__':
app = QApplication(sys.argv)
window = QWidget()
window.show()
sys.exit(app.exec_())
Here’s a breakdown:
import sys
andfrom PyQt5.QtWidgets import QApplication, QWidget
: Imports the required modules.QApplication
manages application flow and settings, whileQWidget
is the base class for UI objects.if __name__ == '__main__':
: Ensures the code runs only when executed directly, not when imported.app = QApplication(sys.argv)
: Creates a QApplication instance.sys.argv
handles command-line arguments.window = QWidget()
: Creates a basic window widget.window.show()
: Makes the window visible.sys.exit(app.exec_())
: Starts the Qt event loop.app.exec_()
returns upon application closure;sys.exit()
cleanly exits Python.
Save this as (e.g.,) basic_window.py
and run it from your terminal: python basic_window.py
. A blank window will appear.
Resizing the Window
Now let’s control the window’s size using the resize()
method.
import sys
from PyQt5.QtWidgets import QApplication, QWidget
if __name__ == '__main__':
app = QApplication(sys.argv)
window = QWidget()
window.resize(400, 300) # Width, Height
window.show()
sys.exit(app.exec_())
Adding window.resize(400, 300)
sets the window to 400 pixels wide and 300 pixels high.
Adding a Window Icon
Finally, let’s add an icon. This needs an image file (e.g., a .ico
file for Windows or a .png
for cross-platform use).
import sys
from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtGui import QIcon
if __name__ == '__main__':
app = QApplication(sys.argv)
window = QWidget()
window.resize(400, 300)
window.setWindowIcon(QIcon('icon.png')) # Replace 'icon.png' with your icon file
window.show()
sys.exit(app.exec_())
We import QIcon
and use window.setWindowIcon(QIcon('icon.png'))
. Replace 'icon.png'
with your icon’s path. Ensure the icon is in the same directory or provide the full path. Remember to install PyQt5: pip install PyQt5
before running.
This concludes the tutorial. You can now expand on this to create more advanced applications.