python-3.x - 如何在 PySide2 中使用 QLabel 加载图像

标签 python-3.x image qlabel qpixmap pyside2

我是编码和 Python 的初学者。我读到 tkinter 有点“基础”,如果你想开发一个稍微复杂一点的应用程序并且 PyQt 在许可方面有问题。这就是为什么我选择 PySide2 来开发 this kind of project , 但到目前为止发现文档相对稀缺。这是正确的选择吗?

我目前的编码问题如下:我尝试使用 PySide2 加载图像但没有成功。这是我 2 次尝试的代码:

尝试 N°1:

import sys
import PySide2
from PySide2.QtWidgets import QApplication, QLabel

app = QApplication(sys.argv)
img = PySide2.QtGui.QImage("/Users/mymac/Downloads/ecg_measure.png")
pixmap=PySide2.QtGui.QPixmap(img)
label = PySide2.QtWidgets.QLabel.setPixmap(pixmap)
label.show()
app.exec_()

我收到以下消息:

Traceback (most recent call last):

File "<ipython-input-1-86961df4959d>", line 8, in <module>
label = PySide2.QtWidgets.QLabel.setPixmap(pixmap)

TypeError: descriptor 'setPixmap' requires a 'PySide2.QtWidgets.QLabel' object but received a 'PySide2.QtGui.QPixmap'

使用 Traceback 中的信息,我尝试了以下尝试 N°2:

import sys
import PySide2
from PySide2.QtWidgets import QApplication, QLabel

app = QApplication(sys.argv)
img = PySide2.QtGui.QImage("/Users/mymac/Downloads/ecg_measure.png")
pixmap=PySide2.QtGui.QPixmap(img)
lab=PySide2.QtWidgets.QLabel(pixmap)
PySide2.QtWidgets.QLabel.setPixmap(lab)
app.exec_()

我收到以下错误消息:

Traceback (most recent call last):

File "<ipython-input-1-61b41e4b2f63>", line 8, in <module>
lab=PySide2.QtWidgets.QLabel(pixmap)

TypeError: 'PySide2.QtWidgets.QLabel' called with wrong argument types:
PySide2.QtWidgets.QLabel(PySide2.QtGui.QPixmap) Supported signatures:
PySide2.QtWidgets.QLabel(PySide2.QtWidgets.QWidget = None, 
PySide2.QtCore.Qt.WindowFlags = Qt.WindowFlags())
PySide2.QtWidgets.QLabel(unicode, PySide2.QtWidgets.QWidget = None, PySide2.QtCore.Qt.WindowFlags = Qt.WindowFlags())

最佳答案

你的代码应该是这样的:

import sys
from PySide2 import QtCore, QtGui, QtWidgets

app = QtWidgets.QApplication(sys.argv)

pixmap = QtGui.QPixmap('/Users/mymac/Downloads/ecg_measure.png')
label = QtWidgets.QLabel()
label.setPixmap(pixmap)    
label.show()

app.exec_()

但是,QLabel 可能不适合您要开发的项目。您很可能需要使用 Graphics View Framework .见 this image viewer example有关提供平移和缩放的基本演示。它是使用 PyQt5 编写的,但您可以轻松地将其转换为 PySide2 - 只需在文件顶部的导入中将 PyQt5 替换为 PySide2,然后替换 pyqtSignal 和第 4 行的 Signal。该示例还需要在当前目录中有一个名为“image.jpg”的图像文件(或者您可以在 loadImage< 中编辑默认路径 方法)。

如果您对 PySide/PyQt 没有太多经验,我建议您使用 this tutorial .它是为 PyQt5 编写的,但 PySide2 的代码将 99% 相同。如上所述,您通常只需要更改导入并删除一些 API 的 pyqt 前缀,例如 pyqtSignalpyqtSlot。可以找到完整的 PySide2 文档 here ,完整的 Qt 文档是 here .

关于python-3.x - 如何在 PySide2 中使用 QLabel 加载图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50209879/

相关文章:

python - 类型错误 : 'float' object not iterable

python - 处理 python 子模块的导入

image - 在房间图像中查找所有不同的对象/封闭多边形

python - 为什么 PyQt5 中的 Qt.AlignCenter onQLabel 对于图像和文本不同?

python - PyQt5如何将QLabel更新为动画

python-3.x - 如何根据列表中的单词创建新的 Pandas 列

python - 使用 pandas read_csv 函数将 'true' 保留为字符串,将 'True' 保留为 bool 值

c - 如何让 C 编程超越控制台?

wpf - 如何分离wpf文本框中的背景图像?

c++ - Qt create和QLabel,为什么会报错?