【问题标题】:How to create a new window with button click [duplicate]如何使用按钮单击创建新窗口[重复]
【发布时间】:2019-09-10 10:22:52
【问题描述】:

我想在单击按钮时创建一个新窗口。稍后我将根据输入的数据动态创建窗口。但我想先从简单的开始。

from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QPushButton, QGridLayout, QWidget

class MyWindow(QtWidgets.QMainWindow, QPushButton):
    def __init__(self):
        super(MyWindow, self).__init__()
        centralWidget = QWidget()
        self.setCentralWidget(centralWidget)
        self.setWindowTitle("ASSET")
        self.Button = QPushButton('Action',self)
        self.Button.clicked.connect(self.Action)
        self.layout = QGridLayout(centralWidget)
        self.layout.addWidget(self.Button)


    def Action(self):
        pass

if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    window = MyWindow()
    window.show()
    sys.exit(app.exec_())

【问题讨论】:

    标签: python pyqt pyqt5


    【解决方案1】:

    您可以创建另一个QMainWindow(),并在单击按钮时激活show() 方法

    from PyQt5 import QtWidgets
    from PyQt5.QtWidgets import QPushButton, QGridLayout, QWidget, QLabel
    
    class NewWindow(QtWidgets.QMainWindow):
        def __init__(self, parent=None):
            super(NewWindow, self).__init__(parent)
    
            self.label = QLabel('New Window!')
            centralWidget = QWidget()
            self.setCentralWidget(centralWidget)
            self.layout = QGridLayout(centralWidget)
            self.layout.addWidget(self.label)
    
    class MyWindow(QtWidgets.QMainWindow, QPushButton):
        def __init__(self):
            super(MyWindow, self).__init__()
            centralWidget = QWidget()
            self.setCentralWidget(centralWidget)
            self.setWindowTitle("ASSET")
            self.Button = QPushButton('Action',self)
            self.Button.clicked.connect(self.Action)
            self.layout = QGridLayout(centralWidget)
            self.layout.addWidget(self.Button)
    
            self.new_window = NewWindow(self)
    
        def Action(self):
            self.new_window.show()
    
    if __name__ == "__main__":
        import sys
    
        app = QtWidgets.QApplication(sys.argv)
        window = MyWindow()
        window.show()
        sys.exit(app.exec_())
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多