直到sys.exit(app.exec_())才会显示任何元素

时间:2019-04-24 22:03:49

标签: python python-3.x pyqt5

我尝试在一个窗口上显示图片(最多6张)。在此之前,您必须在第一个窗口中输入一个名称(以下代码未提供)。 照片会自动从我的相机传输到计算机,因此一开始文件夹中将没有照片,但是一段时间后可能直到6。 通过运行代码,不会出现任何错误,但是当所有6张图像都位于正确的文件夹中时,窗口olny将完全加载。因此,sys.exit(app.exec_())运行之前什么也不会显示。

我尝试在sys.exit(app.exec_())之后打电话给ui.update_picture(MainWindow),但随后Skript停了下来。

from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtGui import QIcon, QPixmap
import sys
import os
import time


path = "C:/Users/benni/Desktop/"                   # given from the first Window
folder_name = "exit_folder_test"                   # given from the first Window
source = "test"                                    # given
os.makedirs(path + folder_name)



class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.resize(1920, 1080)
        self.frame = QtWidgets.QWidget(MainWindow)
        start_x = 20                                # origin from the grid
        start_y = 80                                
        distance = 40                               # distance between the pictures
        global image_width
        image_width = 600                                                       
        global image_height
        image_height = 400

        self.picture1 = QtWidgets.QLabel(self.frame)                                         # all the different fields for the pictures, grid-layout
        self.picture1.setGeometry(QtCore.QRect(start_x, start_y, image_width, image_height))

        self.picture2 = QtWidgets.QLabel(self.frame)
        self.picture2.setGeometry(QtCore.QRect((start_x + image_width + distance), start_y, image_width, image_height))

        self.picture3 = QtWidgets.QLabel(self.frame)
        self.picture3.setGeometry(QtCore.QRect((start_x + 2*image_width + 2*distance), start_y, image_width, image_height))

        self.picture4 = QtWidgets.QLabel(self.frame)
        self.picture4.setGeometry(QtCore.QRect((start_x), (start_y + image_height + distance), image_width, image_height))

        self.picture5 = QtWidgets.QLabel(self.frame)
        self.picture5.setGeometry(QtCore.QRect((start_x + image_width + distance), (start_y + image_height + distance), image_width, image_height))

        self.picture6 = QtWidgets.QLabel(self.frame)
        self.picture6.setGeometry(QtCore.QRect((start_x + 2*image_width + 2*distance), (start_y + image_height + distance), image_width, image_height))

        self.print_button = QtWidgets.QPushButton(self.frame)       
        self.print_button.setGeometry(QtCore.QRect((start_x + 3*image_width + 2*distance) - 74, (start_y + 2*image_height + 2*distance), 75, 24)) 
        MainWindow.setCentralWidget(self.frame)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def update_picture(self, MainWindow):                               # funktions to add pictures to the fields in setupUi
        pixmap1 = QPixmap(path + folder_name + "/image1.jpg").scaled(image_width, image_height)
        self.picture1.setPixmap(pixmap1)
        pixmap2 = QPixmap(path + folder_name + "/image2.jpg").scaled(image_width, image_height)
        self.picture2.setPixmap(pixmap2)
        pixmap3 = QPixmap(path + folder_name + "/image3.jpg").scaled(image_width, image_height)
        self.picture3.setPixmap(pixmap3)
        pixmap4 = QPixmap(path + folder_name + "/image4.jpg").scaled(image_width, image_height)
        self.picture4.setPixmap(pixmap4)
        pixmap5 = QPixmap(path + folder_name + "/image5.jpg").scaled(image_width, image_height)
        self.picture5.setPixmap(pixmap5)
        pixmap6 = QPixmap(path + folder_name + "/image6.jpg").scaled(image_width, image_height)
        self.picture6.setPixmap(pixmap6)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "Fotobox"))
        self.print_button.setText(_translate("MainWindow", "print"))



if __name__ == "__main__":

    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()

    recording = True
    amount = 0
    number = 0
    while recording == True:
        pictures = os.listdir(path + source)         # reads the content of the given folder
        amount_update = len(pictures)         
        if amount != amount_update:                  # checks if the amount of files in the folder has changed
            amount = amount_update 
            for picture_name in pictures:                 
                number += 1
                time.sleep(1)                                   # wait until the picture is transferred
                picture_new_name = "image" + str(number) + ".jpg"
                os.rename(path + source + "/" + picture_name, path + folder_name + "/" + picture_new_name)   # renames all the given pictures and transfer them in a new folder
                if number > 0 and number < 7:           
                    ui.update_picture(MainWindow)
                    print(number)
                else:
                    recording = False
            recording = False



    sys.exit(app.exec_())

1 个答案:

答案 0 :(得分:0)

此问题与app.exec_()无关,问题在于您有一个阻止GUI的任务阻止了它的正确显示,因此在这种情况下,您必须在另一个线程中运行该任务并通知GUI通过信号:

import os
import time
from PyQt5 import QtCore, QtGui, QtWidgets


path = "C:/Users/benni/Desktop/"  # given from the first Window
folder_name = "exit_folder_test"  # given from the first Window
source = "test"
extension = "jpg"

if not os.path.isdir(os.path.join(path, folder_name)):
    os.makedirs(os.path.join(path, folder_name))


class PictureWorker(QtCore.QObject):
    updateSignal = QtCore.pyqtSignal()

    @QtCore.pyqtSlot()
    def search(self):
        recording = True
        number = 0
        amount = 0
        while recording:
            pictures = []
            for file in os.listdir(os.path.join(path, source)):
                if file.endswith(".{}".format(extension)):
                    pictures.append(file)
            amount_update = len(pictures)
            if (
                amount != amount_update
            ):  # checks if the amount of files in the folder has changed
                amount = amount_update
                for picture_name in pictures:
                    number += 1
                    time.sleep(1)  # wait until the picture is transferred
                    picture_new_name = "image{}.{}".format(number, extension)
                    os.rename(
                        os.path.join(path, source, picture_name),
                        os.path.join(path, folder_name, picture_new_name),
                    )  # renames all the given pictures and transfer them in a new folder
                    if 0 < number < 7:
                        print(number)
                        self.updateSignal.emit()
                    else:
                        recording = False
                recording = False


class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        widget = QtWidgets.QWidget()
        self.setCentralWidget(widget)
        grid_layout = QtWidgets.QGridLayout(widget)
        rows, cols = 2, 3
        self._labels = []
        image_width, image_height = 600, 400

        for row in range(rows):
            for col in range(cols):
                label = QtWidgets.QLabel(alignment=QtCore.Qt.AlignCenter)
                label.setFixedSize(image_width, image_height)
                grid_layout.addWidget(label, row, col)
                self._labels.append(label)

        self.print_button = QtWidgets.QPushButton("print")
        grid_layout.addWidget(self.print_button, 3, 3)
        self.resize(1920, 1080)

    def update_image(self):
        for i, label in enumerate(self._labels):
            pixmap = QtGui.QPixmap(
                os.path.join(
                    path, folder_name, "image{}.{}".format(i + 1, extension)
                )
            )
            label.setPixmap(pixmap)


if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    w = MainWindow()
    w.show()
    worker = PictureWorker()
    worker.updateSignal.connect(w.update_image)
    thread = QtCore.QThread()
    thread.start()
    worker.moveToThread(thread)
    QtCore.QTimer.singleShot(0, worker.search)
    sys.exit(app.exec_())