我应该在我的 PyQt 应用程序中使用 `app.exec()` 还是 `app.exec_()`?

2022-01-12 00:00:00 python python-3.x pyqt pyqt5 qt

问题描述

我使用 Python 3 和 PyQt5.这是我的测试 PyQt5 程序,关注最后两行:

I use Python 3 and PyQt5. Here's my test PyQt5 program, focus on the last 2 lines:

from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
import sys

class window(QWidget):
def __init__(self,parent=None):
    super().__init__(parent)
    self.setWindowTitle('test')
    self.resize(250,200)

app=QApplication(sys.argv)
w=window()
w.show()
sys.exit(app.exec())
#sys.exit(app.exec_())

我知道 exec 是 Python 中的语言关键字.但是 Official PyQt5 Documentation 上的代码(特别是 Object Destruction on Exit 部分).我看到该示例显示了 app.exec() 的使用,这让我感到困惑.

I know exec is a language keyword in Python. But code on Official PyQt5 Documentation (specifically the Object Destruction on Exit part). I see that example shows use of app.exec() which confuses me.

当我在我的机器上测试它时.我发现与我的结局没有任何明显的区别.使用和不使用 _ 都会在没有时间差的情况下产生相同的输出.

When I tested it on my machine. I found there is no any visible difference from my end. Both with and without _ produces the same output in no time difference.

我的问题是:

  • 我使用 app.exec() 有什么问题吗?喜欢与 Python 的内部 exec 冲突?我怀疑是因为两个 exec 都在执行某些东西.
  • 如果不能,我可以同时使用两者吗?
  • Is there anything wrong going when I use app.exec()? like clashing with Python's internal exec? I suspect because both exec's are executing something.
  • If not, can I use both interchangeably?

解决方案

那是因为在 Python 3 之前,exec 是一个保留关键字,因此 PyQt 开发人员为其添加了下划线.从 Python 3 开始,exec 不再是保留关键字(因为它是一个内置函数;与 print 的情况相同),所以在 PyQt5 中提供一个不带下划线的版本以与 C++ 文档保持一致是有意义的,但保留一个带下划线的版本是为了向后兼容.所以对于带有 Python 3 的 PyQt5,这两个 exec 函数是相同的.对于较旧的 PyQt,只有 exec_() 可用.

That's because until Python 3, exec was a reserved keyword, so the PyQt devs added underscore to it. From Python 3 onwards, exec is no longer a reserved keyword (because it is a builtin function; same situation as print), so it made sense in PyQt5 to provide a version without an underscore to be consistent with C++ docs, but keep a version with underscore for backwards compatibility. So for PyQt5 with Python 3, the two exec functions are the same. For older PyQt, only exec_() is available.

相关文章