PyQt5 QWidget 代码使用未初始化的变量

PyQt5 QWidget code uses un-initialized variable

我正在学习 zetcode.com 上的教程,我似乎 运行 遇到了麻烦。这段代码应该是非常直接的,所以我把它粘贴在下面。

这都是 QWidget class 实例的一部分(所有 UI 对象的基础 class)。我已经意识到这是我需要理解的基本 classes 之一,以便编写 GUI,我只是对程序中发生的事情感到困惑。

该程序非常简单:PyQt 打开一个 window,然后您可以通过 'x' 按钮退出该 window。单击 'x' 后,会出现一条询问 "Are you sure to quit?" 的消息,允许您继续退出或取消。

import sys
from PyQt5.QtWidgets import QWidget, QMessageBox, QApplication


class Example(QWidget):

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

    self.initUI()


def initUI(self):

    self.setGeometry(300, 300, 250, 150)
    self.setWindowTitle('Message box')
    self.show()

def closeEvent(self, event):

    reply = QMessageBox.question(self, 'Message',
        "Are you sure to quit?", QMessageBox.Yes |
        QMessageBox.No, QMessageBox.No)

    if reply == QMessageBox.Yes:
        event.accept()
    else:
        event.ignore()


if __name__ == '__main__':

app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())

那有什么不合理的? QWidget 调用的 closeEvent() 方法。该方法似乎接受一个从未初始化但以某种方式传递给函数的变量 "event" 。然后在以前从未初始化的对象上调用方法 "event.accept()" 和 "event.ignore()"。

我是PyQt/Qt的菜鸟,可能也是对Python的误解。这是函数 http://doc.qt.io/qt-5/qwidget.html#closeEvent 的文档,可能会澄清一些事情。

The method seemingly accepts a variable "event" that is never initialized but somehow passed into the function.

方法的工作原理。考虑这个简单的函数:

def print_a_word(word):
   print(word)

它有一个我们没有初始化的参数word。当你调用函数时,你需要定义word是什么:

word = "unicorn"
print_a_word(word)

如果您更详细地查看文档,您会发现 event 是一个 QCloseEvent,而它是 "initialized" QWidget

The QCloseEvent class contains parameters that describe a close event.

Close events are sent to widgets that the user wants to close, usually by choosing "Close" from the window menu, or by clicking the X title bar button. They are also sent when you call QWidget::close() to close a widget programmatically.