Skip to content Skip to sidebar Skip to footer

How Do I Open An Image In A Separate Window Using A Button Click In Pyqt5?

from PyQt5.QtWidgets import QApplication, QLabel, QWidget, QFileDialog, QPushButton, QLineEdit,QVBoxLayout, QHBoxLayout from PyQt5.QtCore import * from PyQt5.QtGui import QPixmap f

Solution 1:

You have at least the following errors:

  • The "hbox" created is being added to the window and not to the QDialog: self.setLayout(hbox), it must be mydialog.setLayout(hbox).

  • Do not use the same name for 2 different objects as they can cause problems, in your case there are 2 QPushButton assigned to the variable "self.button2".

  • You try to use the variable "self.label" but never believe it.

Considering the above we can make the following improvements:

  • Use more descriptive names to easily distinguish their function.

  • If you are going to have a window that has a different objective, it is better to create a class.

The above avoid the indicated problems, considering the above the solution is:

import sys

from PyQt5.QtGui import QPixmap
from PyQt5.QtWidgets import (
    QApplication,
    QDialog,
    QFileDialog,
    QHBoxLayout,
    QLabel,
    QPushButton,
    QVBoxLayout,
    QWidget,
)

import Updated_encrypt


classDialog(QDialog):
    def__init__(self, parent=None):
        super().__init__(parent)

        self.load_image_btn = QPushButton("Check Image")
        self.load_image_btn.clicked.connect(self.load_image)

        self.image_lbl = QLabel()
        lay = QVBoxLayout(self)
        lay.addWidget(self.load_image_btn)
        lay.addWidget(self.image_lbl)

    defload_image(self):
        image_path, _ = QFileDialog.getOpenFileName(self, "OpenFile", "", "")
        if image_path:
            updatedImage = Updated_encrypt.decrypt(image_path, 123)
            pixmap = QPixmap(updatedImage)
            self.image_lbl.setPixmap(QPixmap(pixmap))


classWindow(QWidget):
    def__init__(self, parent=None):
        super().__init__(parent)

        self.title = "Encrypt/Decrypt"
        self.InitWindow()

    defInitWindow(self):
        self.setWindowTitle(self.title)
        self.setGeometry(200, 500, 400, 300)

        self.encrypt_btn = QPushButton("Encrypt")
        self.encrypt_btn.clicked.connect(self.openSecondDialog)

        self.decrypt_btn = QPushButton("Decrypt")

        vbox = QVBoxLayout(self)
        vbox.addWidget(self.encrypt_btn)
        vbox.addWidget(self.decrypt_btn)

    defopenSecondDialog(self):

        dialog = Dialog(self)
        dialog.show()


if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(app.exec())

Post a Comment for "How Do I Open An Image In A Separate Window Using A Button Click In Pyqt5?"