简体   繁体   English

如何在pyqt5中设置动态图像路径?

[英]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") “边界半径: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. 我试图动态设置标签上的图像,但是此代码对我不起作用。它显示文件名中的路径正确,但显示空白并且窗口关闭。我也使用了QPixmap,但它不起作用。 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. 另外,您可能需要在打印后执行self.image_label.clear()

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 [0]将是路径字符串。 filename[1] would be non-needed data image (*.jpg *.png *.icon *.gif) . filename [1]将是不需要的数据图像(*.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] . 在python上,您通常以元组,列表或字典的形式获取数据,并且通过指定该数据item[number of index]可以轻松地完成数据的item[number of index] Note that indexes at python starts at 0, not at 1. 请注意,python处的索引从0开始,而不是1。

Example: If I want to pick patata in this list: 示例:如果我要在此列表中选择patata

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]. 我只会使用mytuple[2] ,因为索引[0]是something ,索引[1] nothing patata是, patata是[2],而test是[3]。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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