简体   繁体   中英

how to set dynamic image path in pyqt5?

Here is my code

 def setimage(self):
    self.image_label.setAutoFillBackground(True)
    filename = QtWidgets.QFileDialog.getOpenFileName(self, 'insert image', r'C:\Users\PristineSofts\Demo\Images','image (*.jpg *.png *.icon *.gif)')
    print(filename)
    self.image_label.setStyleSheet("QLabel{border:2px solid #d6d6d6;\n"
                                   "background-image:url(" +filename+ ");\n"

"border-radius:30px;}\\n")

I am trying to set image on label dynamically,but this code is not working for me.It shows path in the filename correct,but it shows blank and window gets closed.I also used QPixmap but it not working. Can anyone help me? Thanks in advanced!

With a label you would do:

 # Make sure you load this library
 from PyQt5.QtGui import QPixmap

 # And then this should work
 def setimage(self):
    filename = QtWidgets.QFileDialog.getOpenFileName(self, 'insert image', r'C:\Users\PristineSofts\Demo\Images','image (*.jpg *.png *.icon *.gif)')
    print("path is " + filename[0] " and I don't need " + filename[1])
    pngfile = QPixmap(filename[0]) # We create the image as a QPixmap widget, using your filename.
    self.image_label.setPixmap(pngfile) # And then we add it like this.

Note: If you still have issues, make sure you provide the path correctly. Also, you might need to do a self.image_label.clear() after your print.

Edit: Filename seems to be a tuple, so you need to choose what item from it you want. filename[0] would be the path string. filename[1] would be non-needed data image (*.jpg *.png *.icon *.gif) .

At python, you get data often in tuples, lists or dicts, and picking that data is easily done by specifying the index of that data item[number of index] . Note that indexes at python starts at 0, not at 1.

Example: If I want to pick patata in this list:

mytuple = ("something", "nothing", "patata", "test")

I would just use mytuple[2] , because the index [0] is something , the index [1] is nothing , patata is [2] and test is [3].

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM