[PYQT5] 主窗口弹出子窗口

﹥>﹥吖頭↗ 提交于 2020-01-19 16:57:38

 需求:

在PYQT5中,点击主窗口中的按钮,弹出子窗口。

测试代码:

例1:

在主窗口添加按钮,并把按钮信号关联槽,在槽函数中创建子窗口对象赋值到普通变量,并调用其 show 方法。

from PyQt5.QtWidgets import *
import sys

class Main(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("主窗口")
        button = QPushButton("弹出子窗", self)
        button.clicked.connect(self.show_child)

    def show_child(self):
        child_window = Child()
        child_window.show()

class Child(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("我是子窗口啊")

# 运行主窗口
if __name__ == "__main__":
    app = QApplication(sys.argv)

    window = Main()
    window.show()

    sys.exit(app.exec_())

运行结果: 该段代码运行后,点击主窗口中的按钮,子窗口一闪而过。

例2:

在主窗口添加按钮,并把按钮信号关联槽,在槽函数中创建子窗口对象并赋值为对象属性,并调用其 show 方法。

from PyQt5.QtWidgets import *
import sys

class Main(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("主窗口")
        button = QPushButton("弹出子窗", self)
        button.clicked.connect(self.show_child)

    def show_child(self):
        self.child_window = Child()
        self.child_window.show()

class Child(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("我是子窗口啊")

# 运行主窗口
if __name__ == "__main__":
    app = QApplication(sys.argv)

    window = Main()
    window.show()

    sys.exit(app.exec_())

运行结果: 该段代码运行后,点击主窗口中的按钮,子窗口正常打开,重复点击按钮,子窗口重复弹出。

例3:

主窗口__init__方法中创建子窗口对象并赋值为对象属性,添加按钮,并把按钮信号关联槽,在槽函数中调用子窗口对象的 show 方法。

from PyQt5.QtWidgets import *
import sys

class Main(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("主窗口")
        button = QPushButton("弹出子窗", self)
        button.clicked.connect(self.show_child)
        self.child_window = Child()

    def show_child(self):
        self.child_window.show()

class Child(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("我是子窗口啊")

# 运行主窗口
if __name__ == "__main__":
    app = QApplication(sys.argv)

    window = Main()
    window.show()

    sys.exit(app.exec_())

运行结果: 重复点击按钮,子窗口不重复弹出。

结论:

例2比例1仅仅多了一个self怎么就运行正常了呢?

  • 例1中 子窗口对象为 方法中普通的变量,当方法运行完后,python的机制就把变量销毁了,故子窗口一闪而过;
  • 例2中 子窗口对象为 主窗口对象的变量,当方法运行完后,主窗口对象依旧存在,故子窗口正常显示,但是每一次运行槽函数都会重新创建子窗口对象;
  • 例3中 子窗口对象为 主窗口对象的变量,当方法运行完后,主窗口对象依旧存在,故子窗口正常显示,每一次运行槽函数只会重新调用子窗口对象;

 

欢迎批评指教。

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!