Search code examples
pyqt5readfileqlabel

Pyqt5: How to setImage in Qlabel if the string in the file is True


Can someone tell me what approach or what logic I can do to setImage in a QLabel? I'm using .setPixmap. I'm making a simple GUI that the image in the Qlabel will change depending in the string in the file.

This is my sample code:

class Ui_MainWindow(object):
def setupUi(self, MainWindow):
    MainWindow.setObjectName("MainWindow")
    MainWindow.resize(508, 338)
    self.centralwidget = QtWidgets.QWidget(MainWindow)
    self.centralwidget.setObjectName("centralwidget")
    self.tabWidget = QtWidgets.QTabWidget(self.centralwidget)
    self.tabWidget.setGeometry(QtCore.QRect(10, 10, 491, 291))
    self.tabWidget.setObjectName("tabWidget")
    self.tab = QtWidgets.QWidget()
    self.tab.setObjectName("tab")
    self.label = QtWidgets.QLabel(self.tab)
    self.label.setGeometry(QtCore.QRect(10, 10, 461, 241))
    self.label.setFrameShape(QtWidgets.QFrame.Box)
    self.label.setText("")
    self.label.setScaledContents(True)
    self.label.setObjectName("label")
    self.tabWidget.addTab(self.tab, "")
    self.tab_2 = QtWidgets.QWidget()
    self.tab_2.setObjectName("tab_2")
    self.label_2 = QtWidgets.QLabel(self.tab_2)
    self.label_2.setGeometry(QtCore.QRect(10, 10, 461, 241))
    self.label_2.setFrameShape(QtWidgets.QFrame.Box)
    self.label_2.setText("")
    self.label_2.setObjectName("label_2")
    self.tabWidget.addTab(self.tab_2, "")
    self.tab_3 = QtWidgets.QWidget()
    self.tab_3.setObjectName("tab_3")
    self.label_3 = QtWidgets.QLabel(self.tab_3)
    self.label_3.setGeometry(QtCore.QRect(10, 10, 461, 241))
    self.label_3.setFrameShape(QtWidgets.QFrame.Box)
    self.label_3.setText("")
    self.label_3.setScaledContents(True)
    self.label_3.setObjectName("label_3")
    self.tabWidget.addTab(self.tab_3, "")
    MainWindow.setCentralWidget(self.centralwidget)
    self.statusbar = QtWidgets.QStatusBar(MainWindow)
    self.statusbar.setObjectName("statusbar")
    MainWindow.setStatusBar(self.statusbar)

    def setImage(self):
    file = open("course","r")
    course = str(file.readlines())
    if course == "Archi":
        self.label.setPixmap(QtGui.QPixmap("ME.jpg"))

Qlabel Where the image will show

enter image description here

The condition is true, what approach should I do to show the image in the Qlabel whenever i run the program?


Solution

  • The setpixmap is correct. It will set the image to the label.

    The problem is with your python code. file.readlines() returns a list. so your if statement is failing.

    In your code, you are comparing ['Archi'] with "Archi", which is false.

    Modify it file.readline() , which returns a string and that should work fine with if statement.

    And ensure setImage function is indented properly.