簡體   English   中英

如何在pyqt5中設置動態圖像路徑?

[英]how to set dynamic image path in pyqt5?

這是我的代碼

 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"

“邊界半徑:30PX;} \\ n”)

我試圖動態設置標簽上的圖像,但是此代碼對我不起作用。它顯示文件名中的路徑正確,但顯示空白並且窗口關閉。我也使用了QPixmap,但它不起作用。 誰能幫我? 提前致謝!

使用標簽,您可以:

 # 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.

注意:如果仍然有問題,請確保正確提供路徑。 另外,您可能需要在打印后執行self.image_label.clear()

編輯:文件名似乎是一個元組,因此您需要從中選擇所需的項目。 filename [0]將是路徑字符串。 filename [1]將是不需要的數據圖像(*.jpg *.png *.icon *.gif)

在python上,您通常以元組,列表或字典的形式獲取數據,並且通過指定該數據item[number of index]可以輕松地完成數據的item[number of index] 請注意,python處的索引從0開始,而不是1。

示例:如果我要在此列表中選擇patata

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

我只會使用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