QLabel不显示pixmap

1 投票
1 回答
5971 浏览
提问于 2025-04-18 17:53

我正在尝试在 QLabel 中显示一个 QPixmap,但是标签却是空的。

这是我的代码:

#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys
from PyQt4 import QtGui

class Test(QtGui.QWidget):

    def __init__(self):
        super(Test, self).__init__()

        self.initUI()

    def initUI(self):      
        pixmap = QtGui.QPixmap("test.png")

        lbl = QtGui.QLabel(self)
        lbl.setPixmap(pixmap)

        self.move(300, 200)
        self.setWindowTitle('Test')
        self.show()        

app = QtGui.QApplication(sys.argv)
ex = Test()
sys.exit(app.exec_())

当我启动应用程序时,窗口是空的:

empty window

我使用的是一个Linux发行版(Manjaro)。我也在Ubuntu上测试过,但遇到同样的问题。

我不明白哪里出了问题,因为我能在 QGraphicsScene 中显示其他的 QPixmap,还可以在 QPushButton 中显示 QIcon

我该如何在我的标签中显示 QPixmap 呢?

编辑:

这是另一个带有布局的版本,但仍然没有解决问题:

#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys
from PyQt4 import QtGui

class Test(QtGui.QWidget):

    def __init__(self):
        super(Test, self).__init__()

        self.initUI()

    def initUI(self):      
        layout = QtGui.QVBoxLayout()
        pixmap = QtGui.QPixmap("test.png")

        lbl = QtGui.QLabel(self)
        lbl.setPixmap(pixmap)

        layout.addWidget(lbl)
        self.setLayout(layout)

        self.move(300, 200)
        self.setWindowTitle('test')
        self.show()        

app = QtGui.QApplication(sys.argv)
ex = Test()
sys.exit(app.exec_())

1 个回答

0

问题不在于路径
问题是在从VSC(Visual Studio Code)运行程序时出现的
如果你在CMD(命令提示符)或终端中运行这个程序,它就能正常运行并显示图像!
我测试过了!

撰写回答