【问题标题】:How to make window be shown not only once while initing another window's class at the same time? [duplicate]如何在同时启动另一个窗口的类时使窗口不仅显示一次? [复制]
【发布时间】:2019-12-07 02:17:48
【问题描述】:

我正在 PyQt5 上制作地址簿,但无法完全显示窗口,因为它只显示一次。

我知道问题的发生是因为我试图在单击按钮时启动类,但这是我想出更新 QLabel 文本的唯一方法,否则窗口将显示而没有任何文本它。

这里有一些代码:

from PyQt5 import QtWidgets
class Window(QtWidgets.QWidget):
    def __init__(self):
        QtWidgets.QWidget.__init__(self)
        self.resize(400,200)
        self.show()
        self.text = ''
        self.button = QtWidgets.QPushButton('Show')
        self.box = QtWidgets.QVBoxLayout()
        self.box.addWidget(self.button)
        self.setLayout(self.box)
        self.button.clicked.connect(self.init)

    def init(self):
        self.text = 'Text'
        win2 = AppearWindow()
        win2.show()

class AppearWindow(QtWidgets.QWidget):
    def __init__(self):
        QtWidgets.QWidget.__init__(self)
        self.resize(100, 50)
        self.label = QtWidgets.QLabel()
        self.label.setText(win.text)
        self.box = QtWidgets.QVBoxLayout()
        self.box.addWidget(self.label)
        self.setLayout(self.box)

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    win = Window()
    sys.exit(app.exec_())

如果我希望在单击主窗口上的按钮时更新其上的 QLabel 文本,如何显示 AppearWindow?

【问题讨论】:

    标签: python python-3.x pyqt pyqt5


    【解决方案1】:

    试试看:

    from PyQt5 import QtWidgets
    import random
    
    class Window(QtWidgets.QWidget):
        def __init__(self):
            super().__init__()
    
            self.text = ''
            self.button = QtWidgets.QPushButton('Show')
            self.button.clicked.connect(self.init)
    
            self.box = QtWidgets.QVBoxLayout()
            self.box.addWidget(self.button)
            self.setLayout(self.box)
    
        def init(self):
            self.text = random.choice(['Text1', 'Text2', 'Text3'])
            self.win2 = AppearWindow(self.text)                         # + self
    
            self.win2.show()                                            # + self
    
    class AppearWindow(QtWidgets.QWidget):
        def __init__(self, text):
            QtWidgets.QWidget.__init__(self)
    
            self.resize(100, 50)
            self.label = QtWidgets.QLabel()
    
    #        self.label.setText(win.text)
            self.label.setText(text)
    
            self.box = QtWidgets.QVBoxLayout()
            self.box.addWidget(self.label)
            self.setLayout(self.box)
    
    if __name__ == "__main__":
        import sys
        app = QtWidgets.QApplication(sys.argv)
        win = Window()
        win.resize(400,200)
        win.show()
        sys.exit(app.exec_())
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-03
      • 2012-09-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多