Python 如何在PyQt5中删除Qlabel

Python 如何在PyQt5中删除Qlabel,python,pyqt,pyqt5,qlabel,Python,Pyqt,Pyqt5,Qlabel,我已经读过一些答案,但它们对我不起作用 这是我的代码: from PyQt5.QtWidgets import QWidget, QCheckBox, QApplication, QHBoxLayout, QLabel from PyQt5.QtCore import Qt from PyQt5.QtGui import QPixmap import sys class Example(QWidget): def __init__(self): super().__in

我已经读过一些答案,但它们对我不起作用

这是我的代码:

from PyQt5.QtWidgets import QWidget, QCheckBox, QApplication, QHBoxLayout, QLabel
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPixmap
import sys

class Example(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):     
        cbAll = QCheckBox('Slice 1', self)              # Slice 1 
        cbAll.move(1200, 130)
        cbAll.toggle()
        cbAll.stateChanged.connect(self.OpenSlice1)

        self.setGeometry(0, 25, 1365, 700)
        self.setWindowTitle('Original Slices')
        self.show()


    def OpenSlice1(self,state):
        pixmap = QPixmap("E:\BEATSON_PROJECT\python\GUI\home.png") 
        self.lbl = QLabel(self)          #Qlabel used to display QPixmap
        self.lbl.setPixmap(pixmap)
        if state == Qt.Checked:
            self.lbl.show()
        else:
            self.lbl.hide()

if __name__ == '__main__':

    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())
但是,当进入未选中选项时,不会隐藏图像:

原始窗口:

选中的切片1窗口:

从这一点上,它总是显示图像,我希望它隐藏它。i、 e打开箱子不起作用:

导致该问题的原因是,每次按下按钮时,您都在创建一个新的
QLabel
,并且分配了相同的变量,因此您无法访问该元素,然后关闭新的
QLabel
,而不是旧的。您必须做的是创建它并仅隐藏它。您可以使用
setVisible()
hide()
show()
方法

class Example(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):     
        cbAll = QCheckBox('Slice 1', self)              # Slice 1 
        cbAll.move(1200, 130)
        cbAll.toggle()
        cbAll.stateChanged.connect(self.OpenSlice1)
        pixmap = QPixmap("E:\BEATSON_PROJECT\python\GUI\home.png") 
        self.lbl = QLabel(self)          #Qlabel used to display QPixmap
        self.lbl.setPixmap(pixmap)
        self.setGeometry(0, 25, 1365, 700)
        self.setWindowTitle('Original Slices')
        self.show()

    def OpenSlice1(self, state):
        self.lbl.setVisible(state != Qt.Unchecked)
        # or
        """if state == Qt.Checked:
            self.lbl.show()
        else:
            self.lbl.hide()"""