Python PyQt program - Image viewer
Write a Python program that builds an image viewer application that displays images using PyQt. Allow users to change the image by clicking "Previous" and "Next" buttons.
From doc.qt.io:
QApplication Class: The QApplication class manages the GUI application's control flow and main settings.
QMainWindow Class: The QMainWindow class provides a main application window.
QWidget: The QWidget class is the base class of all user interface objects.
QVBoxLayout Class: The QVBoxLayout class lines up widgets vertically.
QLabel Class: The QLabel widget provides a text or image display.
QPushButton: The push button, or command button, is perhaps the most commonly used widget in any graphical user interface. Push (click) a button to command the computer to perform some action, or to answer a question. Typical buttons are OK, Apply, Cancel, Close, Yes, No and Help.
QPixmap Class: The QPixmap class is an off-screen image representation that can be used as a paint device.
Qt module: PyQt5 is a set of Python bindings for the Qt application framework. It allows us to use Qt, a popular C++ framework, to create graphical user interfaces (GUIs) in Python.
Sample Solution:
Python Code:
Explanation:
In the exercise above -
- Import the necessary modules.
- Create a "QMainWindow" named "ImageViewerApp" with a central widget.
- Set the window's title and initial size.
- Create a "QLabel" widget (image_label) for displaying images and align it to the center.
- Create "Previous" and "Next" buttons and connect their click events to methods (previous_image and next_image) for navigation.
- Define a list of image file paths ('image_paths') and initialize the image index ('image_index') to 0.
- The "load_image()" method loads and displays the current image based on the current index.
- The "previous_image()" and "next_image()" methods update the image index to navigate through the images and load the corresponding image.
- In the main function, we create the PyQt application, create an instance of the "ImageViewerApp" class, show the window, and run the application's event loop.
Output:
Flowchart:


Go to:
Previous: Customize appearance.
Next: Temperature converter.
Python Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.